From 646954aee3415322b9bfac819b40470a39b7f8e4 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 8 Sep 2026 17:18:58 -0400 Subject: [PATCH 01/32] Add core TypeScript submodules and shared example support --- .github/workflows/ci.yml | 35 + .gitignore | 8 + .prettierignore | 5 + eslint.config.js | 17 + package.json | 2 +- pnpm-lock.yaml | 1253 +++++++++------- pnpm-workspace.yaml | 4 + spacetime-cron-ts/.npmrc | 1 + spacetime-cron-ts/LICENSE.txt | 759 ++++++++++ spacetime-cron-ts/README.md | 389 +++++ spacetime-cron-ts/example/.env.example | 9 + spacetime-cron-ts/example/.npmrc | 1 + spacetime-cron-ts/example/README.md | 202 +++ spacetime-cron-ts/example/package.json | 28 + spacetime-cron-ts/example/public/index.html | 272 ++++ spacetime-cron-ts/example/public/styles.css | 982 ++++++++++++ spacetime-cron-ts/example/server.ts | 52 + spacetime-cron-ts/example/spacetimedb/.npmrc | 1 + .../example/spacetimedb/package.json | 19 + .../example/spacetimedb/src/index.ts | 175 +++ .../example/spacetimedb/tsconfig.json | 13 + spacetime-cron-ts/example/src/app.ts | 449 ++++++ .../module_bindings/app/activity_log_table.ts | 18 + .../module_bindings/app/cleanup_fire_table.ts | 26 + .../module_bindings/app/cron_jobs_table.ts | 30 + .../app/cron_reconcile_tick_table.ts | 17 + .../src/module_bindings/app/cron_run_table.ts | 28 + .../module_bindings/app/digest_fire_table.ts | 26 + .../example/src/module_bindings/app/index.ts | 203 +++ .../app/schedule_cron_reducer.ts | 18 + .../app/schedule_every_reducer.ts | 17 + .../example/src/module_bindings/app/types.ts | 153 ++ .../module_bindings/app/types/procedures.ts | 10 + .../src/module_bindings/app/types/reducers.ts | 16 + .../app/unschedule_job_reducer.ts | 15 + spacetime-cron-ts/example/tsconfig.json | 14 + spacetime-cron-ts/package.json | 69 + .../scripts/sys-abi-test-register.mjs | 19 + spacetime-cron-ts/scripts/test-cron-parser.ts | 210 +++ .../scripts/test-module-local.mjs | 509 +++++++ spacetime-cron-ts/scripts/test-recovery.mjs | 307 ++++ .../scripts/test-registration.ts | 218 +++ spacetime-cron-ts/scripts/test-schedule.ts | 199 +++ spacetime-cron-ts/scripts/test-types.ts | 72 + spacetime-cron-ts/scripts/test-validation.ts | 97 ++ spacetime-cron-ts/spacetimedb/.npmrc | 1 + spacetime-cron-ts/spacetimedb/package.json | 19 + spacetime-cron-ts/spacetimedb/src/index.ts | 336 +++++ spacetime-cron-ts/spacetimedb/tsconfig.json | 12 + spacetime-cron-ts/src/cron.ts | 1137 ++++++++++++++ spacetime-cron-ts/src/index.ts | 29 + spacetime-cron-ts/src/parser.ts | 58 + spacetime-cron-ts/src/schedule.ts | 184 +++ spacetime-cron-ts/src/sys-abi.d.ts | 10 + spacetime-cron-ts/src/types.ts | 164 +++ spacetime-cron-ts/tsconfig.json | 15 + spacetime-crypto-ts/.npmrc | 1 + spacetime-crypto-ts/LICENSE.txt | 759 ++++++++++ spacetime-crypto-ts/README.md | 71 + spacetime-crypto-ts/package.json | 59 + spacetime-crypto-ts/scripts/test-vectors.ts | 340 +++++ spacetime-crypto-ts/src/hmac.ts | 6 + spacetime-crypto-ts/src/index.ts | 17 + spacetime-crypto-ts/src/sha256.ts | 8 + spacetime-crypto-ts/src/timing.ts | 111 ++ spacetime-crypto-ts/src/vendors.ts | 160 ++ spacetime-crypto-ts/tsconfig.json | 14 + spacetime-rate-limit-ts/.npmrc | 1 + spacetime-rate-limit-ts/LICENSE.txt | 759 ++++++++++ spacetime-rate-limit-ts/README.md | 152 ++ spacetime-rate-limit-ts/example/.env.example | 4 + spacetime-rate-limit-ts/example/.npmrc | 1 + spacetime-rate-limit-ts/example/README.md | 178 +++ spacetime-rate-limit-ts/example/package.json | 29 + .../example/public/index.html | 174 +++ .../example/public/styles.css | 1310 +++++++++++++++++ spacetime-rate-limit-ts/example/public/ui.js | 763 ++++++++++ .../example/scripts/test-reactor-rules.ts | 44 + spacetime-rate-limit-ts/example/server.ts | 42 + .../example/spacetimedb/.npmrc | 1 + .../example/spacetimedb/package.json | 19 + .../example/spacetimedb/src/index.ts | 1130 ++++++++++++++ .../example/spacetimedb/src/model.ts | 74 + .../example/spacetimedb/src/reactor-rules.ts | 216 +++ .../example/spacetimedb/src/schema.ts | 52 + .../example/spacetimedb/tsconfig.json | 11 + spacetime-rate-limit-ts/example/src/app.ts | 436 ++++++ .../app/buy_upgrade_procedure.ts | 20 + .../example/src/module_bindings/app/index.ts | 257 ++++ .../app/overcharge_procedure.ts | 19 + .../rateLimit/add_rate_limit_admin_reducer.ts | 15 + .../admin_rate_limit_buckets_table.ts | 20 + .../app/rateLimit/consume_procedure.ts | 24 + .../app/rateLimit/rate_limit_config_table.ts | 17 + .../app/rateLimit/reset_buckets_reducer.ts | 15 + .../app/rateLimit/run_sweep_procedure.ts | 16 + .../module_bindings/app/rateLimit/types.ts | 56 + .../app/rateLimit/update_config_reducer.ts | 15 + .../app/rate_limit_demo_config_table.ts | 18 + .../app/rate_limit_events_admin_table.ts | 26 + .../app/reactor_events_table.ts | 25 + .../app/reactor_limit_status_table.ts | 21 + .../app/reactor_players_table.ts | 24 + .../module_bindings/app/reactor_shop_table.ts | 21 + .../app/reactor_state_table.ts | 31 + .../app/repair_reactor_procedure.ts | 19 + .../module_bindings/app/reset_demo_reducer.ts | 13 + .../app/run_sweep_procedure.ts | 16 + .../app/set_player_color_reducer.ts | 15 + .../app/start_reactor_procedure.ts | 19 + .../app/tap_reactor_procedure.ts | 19 + .../example/src/module_bindings/app/types.ts | 157 ++ .../module_bindings/app/types/procedures.ts | 28 + .../src/module_bindings/app/types/reducers.ts | 16 + .../app/update_config_reducer.ts | 17 + spacetime-rate-limit-ts/example/tsconfig.json | 15 + spacetime-rate-limit-ts/package.json | 64 + spacetime-rate-limit-ts/scripts/test.ts | 182 +++ spacetime-rate-limit-ts/spacetimedb/.npmrc | 1 + .../spacetimedb/package.json | 19 + .../spacetimedb/src/index.ts | 17 + .../spacetimedb/tsconfig.json | 12 + spacetime-rate-limit-ts/src/index.ts | 17 + spacetime-rate-limit-ts/src/key.ts | 7 + spacetime-rate-limit-ts/src/limit.ts | 297 ++++ spacetime-rate-limit-ts/src/submodule.ts | 28 + .../src/submodule/install.ts | 12 + .../src/submodule/operations.ts | 193 +++ .../src/submodule/schema.ts | 63 + spacetime-rate-limit-ts/tsconfig.json | 15 + spacetime-retry-ts/.npmrc | 1 + spacetime-retry-ts/LICENSE.txt | 759 ++++++++++ spacetime-retry-ts/README.md | 120 ++ spacetime-retry-ts/package.json | 60 + spacetime-retry-ts/scripts/test.ts | 45 + spacetime-retry-ts/spacetimedb/.npmrc | 1 + spacetime-retry-ts/spacetimedb/package.json | 19 + spacetime-retry-ts/spacetimedb/src/index.ts | 114 ++ spacetime-retry-ts/spacetimedb/tsconfig.json | 12 + spacetime-retry-ts/src/handler.ts | 54 + spacetime-retry-ts/src/index.ts | 9 + spacetime-retry-ts/src/submodule.ts | 329 +++++ spacetime-retry-ts/tsconfig.json | 15 + spacetime-submodule-shared-ts/.npmrc | 1 + .../assets/brand.svg | 17 + spacetime-submodule-shared-ts/assets/logo.svg | 5 + spacetime-submodule-shared-ts/package.json | 34 + .../scripts/auth.test.ts | 139 ++ .../scripts/server.test.ts | 65 + .../src/auth-panel.ts | 448 ++++++ spacetime-submodule-shared-ts/src/icons.ts | 51 + spacetime-submodule-shared-ts/src/index.ts | 11 + spacetime-submodule-shared-ts/src/server.ts | 73 + .../src/styles/index.css | 253 ++++ spacetime-submodule-shared-ts/tsconfig.json | 13 + 155 files changed, 19920 insertions(+), 503 deletions(-) create mode 100644 spacetime-cron-ts/.npmrc create mode 100644 spacetime-cron-ts/LICENSE.txt create mode 100644 spacetime-cron-ts/README.md create mode 100644 spacetime-cron-ts/example/.env.example create mode 100644 spacetime-cron-ts/example/.npmrc create mode 100644 spacetime-cron-ts/example/README.md create mode 100644 spacetime-cron-ts/example/package.json create mode 100644 spacetime-cron-ts/example/public/index.html create mode 100644 spacetime-cron-ts/example/public/styles.css create mode 100644 spacetime-cron-ts/example/server.ts create mode 100644 spacetime-cron-ts/example/spacetimedb/.npmrc create mode 100644 spacetime-cron-ts/example/spacetimedb/package.json create mode 100644 spacetime-cron-ts/example/spacetimedb/src/index.ts create mode 100644 spacetime-cron-ts/example/spacetimedb/tsconfig.json create mode 100644 spacetime-cron-ts/example/src/app.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/activity_log_table.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/cleanup_fire_table.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/cron_jobs_table.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/cron_reconcile_tick_table.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/cron_run_table.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/digest_fire_table.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/index.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/schedule_cron_reducer.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/schedule_every_reducer.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/types.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/types/procedures.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/types/reducers.ts create mode 100644 spacetime-cron-ts/example/src/module_bindings/app/unschedule_job_reducer.ts create mode 100644 spacetime-cron-ts/example/tsconfig.json create mode 100644 spacetime-cron-ts/package.json create mode 100644 spacetime-cron-ts/scripts/sys-abi-test-register.mjs create mode 100644 spacetime-cron-ts/scripts/test-cron-parser.ts create mode 100644 spacetime-cron-ts/scripts/test-module-local.mjs create mode 100644 spacetime-cron-ts/scripts/test-recovery.mjs create mode 100644 spacetime-cron-ts/scripts/test-registration.ts create mode 100644 spacetime-cron-ts/scripts/test-schedule.ts create mode 100644 spacetime-cron-ts/scripts/test-types.ts create mode 100644 spacetime-cron-ts/scripts/test-validation.ts create mode 100644 spacetime-cron-ts/spacetimedb/.npmrc create mode 100644 spacetime-cron-ts/spacetimedb/package.json create mode 100644 spacetime-cron-ts/spacetimedb/src/index.ts create mode 100644 spacetime-cron-ts/spacetimedb/tsconfig.json create mode 100644 spacetime-cron-ts/src/cron.ts create mode 100644 spacetime-cron-ts/src/index.ts create mode 100644 spacetime-cron-ts/src/parser.ts create mode 100644 spacetime-cron-ts/src/schedule.ts create mode 100644 spacetime-cron-ts/src/sys-abi.d.ts create mode 100644 spacetime-cron-ts/src/types.ts create mode 100644 spacetime-cron-ts/tsconfig.json create mode 100644 spacetime-crypto-ts/.npmrc create mode 100644 spacetime-crypto-ts/LICENSE.txt create mode 100644 spacetime-crypto-ts/README.md create mode 100644 spacetime-crypto-ts/package.json create mode 100644 spacetime-crypto-ts/scripts/test-vectors.ts create mode 100644 spacetime-crypto-ts/src/hmac.ts create mode 100644 spacetime-crypto-ts/src/index.ts create mode 100644 spacetime-crypto-ts/src/sha256.ts create mode 100644 spacetime-crypto-ts/src/timing.ts create mode 100644 spacetime-crypto-ts/src/vendors.ts create mode 100644 spacetime-crypto-ts/tsconfig.json create mode 100644 spacetime-rate-limit-ts/.npmrc create mode 100644 spacetime-rate-limit-ts/LICENSE.txt create mode 100644 spacetime-rate-limit-ts/README.md create mode 100644 spacetime-rate-limit-ts/example/.env.example create mode 100644 spacetime-rate-limit-ts/example/.npmrc create mode 100644 spacetime-rate-limit-ts/example/README.md create mode 100644 spacetime-rate-limit-ts/example/package.json create mode 100644 spacetime-rate-limit-ts/example/public/index.html create mode 100644 spacetime-rate-limit-ts/example/public/styles.css create mode 100644 spacetime-rate-limit-ts/example/public/ui.js create mode 100644 spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts create mode 100644 spacetime-rate-limit-ts/example/server.ts create mode 100644 spacetime-rate-limit-ts/example/spacetimedb/.npmrc create mode 100644 spacetime-rate-limit-ts/example/spacetimedb/package.json create mode 100644 spacetime-rate-limit-ts/example/spacetimedb/src/index.ts create mode 100644 spacetime-rate-limit-ts/example/spacetimedb/src/model.ts create mode 100644 spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts create mode 100644 spacetime-rate-limit-ts/example/spacetimedb/src/schema.ts create mode 100644 spacetime-rate-limit-ts/example/spacetimedb/tsconfig.json create mode 100644 spacetime-rate-limit-ts/example/src/app.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/buy_upgrade_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/overcharge_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/add_rate_limit_admin_reducer.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/admin_rate_limit_buckets_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/consume_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/rate_limit_config_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/reset_buckets_reducer.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/run_sweep_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/update_config_reducer.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_demo_config_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_events_admin_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_events_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_limit_status_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_players_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_shop_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_state_table.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/repair_reactor_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/reset_demo_reducer.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/run_sweep_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/set_player_color_reducer.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/start_reactor_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/tap_reactor_procedure.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/types.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/types/procedures.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/types/reducers.ts create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/update_config_reducer.ts create mode 100644 spacetime-rate-limit-ts/example/tsconfig.json create mode 100644 spacetime-rate-limit-ts/package.json create mode 100644 spacetime-rate-limit-ts/scripts/test.ts create mode 100644 spacetime-rate-limit-ts/spacetimedb/.npmrc create mode 100644 spacetime-rate-limit-ts/spacetimedb/package.json create mode 100644 spacetime-rate-limit-ts/spacetimedb/src/index.ts create mode 100644 spacetime-rate-limit-ts/spacetimedb/tsconfig.json create mode 100644 spacetime-rate-limit-ts/src/index.ts create mode 100644 spacetime-rate-limit-ts/src/key.ts create mode 100644 spacetime-rate-limit-ts/src/limit.ts create mode 100644 spacetime-rate-limit-ts/src/submodule.ts create mode 100644 spacetime-rate-limit-ts/src/submodule/install.ts create mode 100644 spacetime-rate-limit-ts/src/submodule/operations.ts create mode 100644 spacetime-rate-limit-ts/src/submodule/schema.ts create mode 100644 spacetime-rate-limit-ts/tsconfig.json create mode 100644 spacetime-retry-ts/.npmrc create mode 100644 spacetime-retry-ts/LICENSE.txt create mode 100644 spacetime-retry-ts/README.md create mode 100644 spacetime-retry-ts/package.json create mode 100644 spacetime-retry-ts/scripts/test.ts create mode 100644 spacetime-retry-ts/spacetimedb/.npmrc create mode 100644 spacetime-retry-ts/spacetimedb/package.json create mode 100644 spacetime-retry-ts/spacetimedb/src/index.ts create mode 100644 spacetime-retry-ts/spacetimedb/tsconfig.json create mode 100644 spacetime-retry-ts/src/handler.ts create mode 100644 spacetime-retry-ts/src/index.ts create mode 100644 spacetime-retry-ts/src/submodule.ts create mode 100644 spacetime-retry-ts/tsconfig.json create mode 100644 spacetime-submodule-shared-ts/.npmrc create mode 100644 spacetime-submodule-shared-ts/assets/brand.svg create mode 100644 spacetime-submodule-shared-ts/assets/logo.svg create mode 100644 spacetime-submodule-shared-ts/package.json create mode 100644 spacetime-submodule-shared-ts/scripts/auth.test.ts create mode 100644 spacetime-submodule-shared-ts/scripts/server.test.ts create mode 100644 spacetime-submodule-shared-ts/src/auth-panel.ts create mode 100644 spacetime-submodule-shared-ts/src/icons.ts create mode 100644 spacetime-submodule-shared-ts/src/index.ts create mode 100644 spacetime-submodule-shared-ts/src/server.ts create mode 100644 spacetime-submodule-shared-ts/src/styles/index.css create mode 100644 spacetime-submodule-shared-ts/tsconfig.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f7a1d9ee0c..d4c1706ed96 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1655,3 +1655,38 @@ jobs: # - name: Print rows in the user table # if: always() # run: spacetime sql quickstart-chat "SELECT * FROM user" + + typescript-submodules: + needs: [merge_queue_noop] + if: ${{ needs.merge_queue_noop.outputs.skip != 'true' }} + name: TypeScript - Submodules + runs-on: spacetimedb-new-runner-2 + 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 + + - name: Install released SpacetimeDB toolchain + run: | + curl -sSf https://install.spacetimedb.com | sh -s -- --root-dir "$RUNNER_TEMP/spacetime" --yes + echo "$RUNNER_TEMP/spacetime" >> "$GITHUB_PATH" + "$RUNNER_TEMP/spacetime/spacetime" version install 2.8.3 --use --yes + + - 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..ea0cb1c5e9e --- /dev/null +++ b/spacetime-cron-ts/LICENSE.txt @@ -0,0 +1,759 @@ +SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT + +Business Source License 1.1 + +Parameters + +Licensor: Clockwork Laboratories, Inc. +Licensed Work: SpacetimeDB 2.8.3 + The Licensed Work is + (c) 2023 Clockwork Laboratories, Inc. + +Additional Use Grant: You may make use of the Licensed Work provided your + application or service uses the Licensed Work with no + more than one SpacetimeDB instance in production and + provided that you do not use the Licensed Work for a + Database Service. + + A “Database Service” is a commercial offering that + allows third parties (other than your employees and + contractors) to access the functionality of the + Licensed Work by creating tables whose schemas are + controlled by such third parties. + +Change Date: 2031-08-18 + +Change License: GNU Affero General Public License v3.0 with a linking + exception + +For information about alternative licensing arrangements for the Software, +please visit: https://spacetimedb.com + +Notice + +The Business Source License (this document, or the “License”) is not an Open +Source license. However, the Licensed Work will eventually be made available +under an Open Source License, as stated in this License. + +License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. +“Business Source License” is a trademark of MariaDB Corporation Ab. + +----------------------------------------------------------------------------- + +Base License and Subdirectory Specific Licenses + +1. Repository-Wide License +Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. + +2. Subdirectory-Specific Licenses +Certain subdirectories within this repository are licensed under different terms. + +If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. + +In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. + +3. Contributor Acknowledgement +By contributing to this repository, you agree that: + +Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. + +If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. + +4. Reading the Applicable License +Before using, modifying, or distributing code from this repository, you must read: + +This base LICENSE.txt file for the overall repository license. + +Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. + +----------------------------------------------------------------------------- + +Business Source License 1.1 + +Terms + +The Licensor hereby grants you the right to copy, modify, create derivative +works, redistribute, and make non-production use of the Licensed Work. The +Licensor may make an Additional Use Grant, above, permitting limited +production use. + +Effective on the Change Date, or the fourth anniversary of the first publicly +available distribution of a specific version of the Licensed Work under this +License, whichever comes first, the Licensor hereby grants you rights under +the terms of the Change License, and the rights granted in the paragraph +above terminate. + +If your use of the Licensed Work does not comply with the requirements +currently in effect as described in this License, you must purchase a +commercial license from the Licensor, its affiliated entities, or authorized +resellers, or you must refrain from using the Licensed Work. + +All copies of the original and modified Licensed Work, and derivative works +of the Licensed Work, are subject to this License. This License applies +separately for each version of the Licensed Work and the Change Date may vary +for each version of the Licensed Work released by Licensor. + +You must conspicuously display this License on each original or modified copy +of the Licensed Work. If you receive the Licensed Work in original or +modified form from a third party, the terms and conditions set forth in this +License apply to your use of that work. + +Any use of the Licensed Work in violation of this License will automatically +terminate your rights under this License for the current and all other +versions of the Licensed Work. + +This License does not grant you any right in any trademark or logo of +Licensor or its affiliates (provided that you may use a trademark or logo of +Licensor as expressly required by this License). + +TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON +AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, +EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND +TITLE. + +MariaDB hereby grants you permission to use this License’s text to license +your works, and to refer to it using the trademark “Business Source License”, +as long as you comply with the Covenants of Licensor below. + +Covenants of Licensor + +In consideration of the right to use this License’s text and the “Business +Source License” name and trademark, Licensor covenants to MariaDB, and to all +other recipients of the licensed work to be provided by Licensor: + +1. To specify as the Change License the GPL Version 2.0 or any later version, + or a license that is compatible with GPL Version 2.0 or a later version, + where “compatible” means that software provided under the Change License can + be included in a program with software provided under GPL Version 2.0 or a + later version. Licensor may specify additional Change Licenses without + limitation. + +2. To either: (a) specify an additional grant of rights to use that does not + impose any additional restriction on the right granted in this License, as + the Additional Use Grant; or (b) insert the text “None”. + +3. To specify a Change Date. + +4. Not to modify this License in any other way. + +----------------------------------------------------------------------------- + +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License, version 3, as published +by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License +along with this program; if not, see . + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission to convey the resulting work. + +Additional permission under GNU AGPL version 3 section 13 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission that, notwithstanding any other provision of this +License, you need not prominently offer all users interacting with your +modified version remotely through a computer network an opportunity to +receive the Corresponding Source of your version from a network server at no +charge, if your version supports such interaction. This permission does not +waive or modify any other obligations or terms of the AGPL v3.0, except for +the specific requirement set forth in section 13. + +A copy of the AGPL v3.0 license is reproduced below. + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs, and that you know you can +do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the +software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free +software are heartened and encouraged by the resulting cooperation. However, +in the case of software used on network servers, this result may fail to come +about. The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its source +code to the public. + +The GNU Affero General Public License is designed specifically to ensure +that, in such cases, the modified source code becomes available to the +community. It requires the operator of a network server to provide the source +code of the modified version running there to the users of that server. +Therefore, public use of a modified version, on a publicly accessible server, +gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different +license, not a version of the Affero GPL, but Affero has released a new +version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be +individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a +fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under +applicable copyright law, except executing it on a computer or modifying a +private copy. Propagation includes copying, distribution (with or without +modification), making available to the public, and in some countries other +activities as well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that (1) +displays an appropriate copyright notice, and (2) tells the user that there +is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how to +view a copy of this License. If the interface presents a list of user +commands or options, such as a menu, a prominent item in the list meets this +criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces +specified for a particular programming language, one that is widely used +among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the +work as a whole, that (a) is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and (b) serves only +to enable use of the work with that Major Component, or to implement a +Standard Interface for which an implementation is available to the public in +source code form. A "Major Component", in this context, means a major +essential component (kernel, window system, and so on) of the specific +operating system (if any) on which the executable work runs, or a compiler +used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the +source code needed to generate, install, and (for an executable work) run the +object code and to modify the work, including scripts to control those +activities. However, it does not include the work's System Libraries, or +general-purpose tools or generally available free programs which are used +unmodified in performing those activities but which are not part of the work. +For example, Corresponding Source includes interface definition files +associated with source files for the work, and the source code for shared +libraries and dynamically linked subprograms that the work is specifically +designed to require, such as by intimate data communication or control flow +between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the +unmodified Program. The output from running a covered work is covered by this +License only if the output, given its content, constitutes a covered work. +This License acknowledges your rights of fair use or other equivalent, as +provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make +modifications exclusively for you, or provide you with facilities for running +those works, provided that you comply with the terms of this License in +conveying all material for which you do not control copyright. Those thus +making or running the covered works for you must do so exclusively on your +behalf, under your direction and control, on terms that prohibit them from +making any copies of your copyrighted material outside their relationship +with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes it +unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention is +effected by exercising rights under this License with respect to the covered +work, and you disclaim any intention to limit operation or modification of +the work as a means of enforcing, against the work's users, your or third +parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section 7 +apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section 4, +provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement +modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, and +all its parts, regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do not +display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of a +storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to the +other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by a written offer, valid for at +least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium +customarily used for software interchange, for a price no more than your +reasonable cost of physically performing this conveying of source, or (2) +access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source in +the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the +Corresponding Source may be on a different server (operated by you or a third +party) that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the Corresponding +Source, you remain obligated to ensure that it is available for as long as +needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you +inform other peers where the object code and Corresponding Source of the work +are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in +conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a +particular user, "normally used" refers to a typical or common use of that +class of product, regardless of the status of the particular user or of the +way in which the particular user actually uses, or expects or is expected to +use, the product. A product is a consumer product regardless of whether the +product has substantial commercial, industrial or non-consumer uses, unless +such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified +version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case +prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part of +a transaction in which the right of possession and use of the User Product is +transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed +under this section must be accompanied by the Installation Information. But +this requirement does not apply if neither you nor any third party retains +the ability to install modified object code on the User Product (for example, +the work has been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates for +a work that has been modified or installed by the recipient, or for the User +Product in which it has been modified or installed. Access to a network may +be denied when the modification itself materially and adversely affects the +operation of the network or violates the rules and protocols for +communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in +accord with this section must be in a format that is publicly documented (and +with an implementation available to the public in source code form), and must +require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional +permissions that are applicable to the entire Program shall be treated as +though they were included in this License, to the extent that they are valid +under applicable law. If additional permissions apply only to part of the +Program, that part may be used separately under those permissions, but the +entire Program remains governed by this License without regard to the +additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate +copyright permission. + +Notwithstanding any other provision of this License, for material you add to +a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as +different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these +contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is governed +by this License along with a term that is a further restriction, you may +remove that term. If a license document contains a further restriction but +permits relicensing or conveying under this License, you may add to a covered +work material governed by the terms of that license document, provided that +the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must +place, in the relevant source files, a statement of the additional terms that +apply to those files, or a notice indicating where to find the applicable +terms. + +Additional terms, permissive or non-permissive, may be stated in the form of +a separately written license, or stated as exceptions; the above requirements +apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated (a) provisionally, unless and until +the copyright holder explicitly and finally terminates your license, and (b) +permanently, if the copyright holder fails to notify you of the violation by +some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by some +reasonable means, this is the first time you have received notice of +violation of this License (for any work) from that copyright holder, and you +cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. If +your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as a +consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions +infringe copyright if you do not accept this License. Therefore, by modifying +or propagating a covered work, you indicate your acceptance of this License +to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a +license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance by +third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who +receives a copy of the work also receives whatever licenses to the work the +party's predecessor in interest had or could give under the previous +paragraph, plus a right to possession of the Corresponding Source of the work +from the predecessor in interest, if the predecessor has it or can get it +with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim or +counterclaim in a lawsuit) alleging that any patent claim is infringed by +making, using, selling, offering for sale, or importing the Program or any +portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus +licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter +acquired, that would be infringed by some manner, permitted by this License, +of making, using, or selling its contributor version, but do not include +claims that would be infringed only as a consequence of further modification +of the contributor version. For purposes of this definition, "control" +includes the right to grant patent sublicenses in a manner consistent with +the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent (such +as an express permission to practice a patent or covenant not to sue for +patent infringement). To "grant" such a patent license to a party means to +make such an agreement or commitment not to enforce a patent against the +party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of +charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, to +extend the patent license to downstream recipients. "Knowingly relying" means +you have actual knowledge that, but for the patent license, your conveying +the covered work in a country, or your recipient's use of the covered work in +a country, would infringe one or more identifiable patents in that country +that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and +grant a patent license to some of the parties receiving the covered work +authorizing them to use, propagate, modify or convey a specific copy of the +covered work, then the patent license you grant is automatically extended to +all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the +non-exercise of one or more of the rights that are specifically granted under +this License. You may not convey a covered work if you are a party to an +arrangement with a third party that is in the business of distributing +software, under which you make payment to the third party based on the extent +of your activity of conveying the work, and under which the third party +grants, to any of the parties who would receive the covered work from you, a +discriminatory patent license (a) in connection with copies of the covered +work conveyed by you (or copies made from those copies), or (b) primarily for +and in connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any +implied license or other defenses to infringement that may otherwise be +available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not excuse +you from the conditions of this License. If you cannot convey a covered work +so as to satisfy simultaneously your obligations under this License and any +other pertinent obligations, then as a consequence you may not convey it at +all. For example, if you agree to terms that obligate you to collect a +royalty for further conveying from those to whom you convey the Program, the +only way you could satisfy both those terms and this License would be to +refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users interacting +with it remotely through a computer network (if your version supports such +interaction) an opportunity to receive the Corresponding Source of your +version by providing access to the Corresponding Source from a network server +at no charge, through some standard or customary means of facilitating +copying of software. This Corresponding Source shall include the +Corresponding Source for any work covered by version 3 of the GNU General +Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or of any +later version published by the Free Software Foundation. If the Program does +not specify a version number of the GNU Affero General Public License, you +may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the +GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or copyright +holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. +SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY +SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE +OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR +DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR +A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above +cannot be given local legal effect according to their terms, reviewing courts +shall apply local law that most closely approximates an absolute waiver of +all civil liability in connection with the Program, unless a warranty or +assumption of liability accompanies a copy of the Program in return for a +fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + +SpacetimeDB: A database which replaces your server. +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could +display a "Source" link that leads users to an archive of the code. There are +many ways you could offer source, and different solutions will be better for +different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if +any, to sign a "copyright disclaimer" for the program, if necessary. For more +information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md new file mode 100644 index 00000000000..21f12bff947 --- /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 + +- SpacetimeDB CLI 2.8.3 +- `spacetimedb` npm package 2.8.3 +- 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@^2.8.3 +``` + +`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 + +BUSL-1.1. 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..d6080ed7558 --- /dev/null +++ b/spacetime-cron-ts/example/README.md @@ -0,0 +1,202 @@ +# 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 +- SpacetimeDB CLI 2.8.3 with `spacetime:sys@2.0` volatile procedure support +- A local SpacetimeDB server + +Select the supported CLI release: + +```powershell +spacetime version install 2.8.3 +spacetime version use 2.8.3 +``` + +## 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@^2.8.3 +``` + +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..cac97144152 --- /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.8.3 (commit 8e410d2842147bd8e5a32a9589cc00c19f7478e2). + +/* 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.8.3" 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..d7469942d48 --- /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": "BUSL-1.1", + "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..ea0cb1c5e9e --- /dev/null +++ b/spacetime-crypto-ts/LICENSE.txt @@ -0,0 +1,759 @@ +SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT + +Business Source License 1.1 + +Parameters + +Licensor: Clockwork Laboratories, Inc. +Licensed Work: SpacetimeDB 2.8.3 + The Licensed Work is + (c) 2023 Clockwork Laboratories, Inc. + +Additional Use Grant: You may make use of the Licensed Work provided your + application or service uses the Licensed Work with no + more than one SpacetimeDB instance in production and + provided that you do not use the Licensed Work for a + Database Service. + + A “Database Service” is a commercial offering that + allows third parties (other than your employees and + contractors) to access the functionality of the + Licensed Work by creating tables whose schemas are + controlled by such third parties. + +Change Date: 2031-08-18 + +Change License: GNU Affero General Public License v3.0 with a linking + exception + +For information about alternative licensing arrangements for the Software, +please visit: https://spacetimedb.com + +Notice + +The Business Source License (this document, or the “License”) is not an Open +Source license. However, the Licensed Work will eventually be made available +under an Open Source License, as stated in this License. + +License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. +“Business Source License” is a trademark of MariaDB Corporation Ab. + +----------------------------------------------------------------------------- + +Base License and Subdirectory Specific Licenses + +1. Repository-Wide License +Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. + +2. Subdirectory-Specific Licenses +Certain subdirectories within this repository are licensed under different terms. + +If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. + +In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. + +3. Contributor Acknowledgement +By contributing to this repository, you agree that: + +Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. + +If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. + +4. Reading the Applicable License +Before using, modifying, or distributing code from this repository, you must read: + +This base LICENSE.txt file for the overall repository license. + +Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. + +----------------------------------------------------------------------------- + +Business Source License 1.1 + +Terms + +The Licensor hereby grants you the right to copy, modify, create derivative +works, redistribute, and make non-production use of the Licensed Work. The +Licensor may make an Additional Use Grant, above, permitting limited +production use. + +Effective on the Change Date, or the fourth anniversary of the first publicly +available distribution of a specific version of the Licensed Work under this +License, whichever comes first, the Licensor hereby grants you rights under +the terms of the Change License, and the rights granted in the paragraph +above terminate. + +If your use of the Licensed Work does not comply with the requirements +currently in effect as described in this License, you must purchase a +commercial license from the Licensor, its affiliated entities, or authorized +resellers, or you must refrain from using the Licensed Work. + +All copies of the original and modified Licensed Work, and derivative works +of the Licensed Work, are subject to this License. This License applies +separately for each version of the Licensed Work and the Change Date may vary +for each version of the Licensed Work released by Licensor. + +You must conspicuously display this License on each original or modified copy +of the Licensed Work. If you receive the Licensed Work in original or +modified form from a third party, the terms and conditions set forth in this +License apply to your use of that work. + +Any use of the Licensed Work in violation of this License will automatically +terminate your rights under this License for the current and all other +versions of the Licensed Work. + +This License does not grant you any right in any trademark or logo of +Licensor or its affiliates (provided that you may use a trademark or logo of +Licensor as expressly required by this License). + +TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON +AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, +EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND +TITLE. + +MariaDB hereby grants you permission to use this License’s text to license +your works, and to refer to it using the trademark “Business Source License”, +as long as you comply with the Covenants of Licensor below. + +Covenants of Licensor + +In consideration of the right to use this License’s text and the “Business +Source License” name and trademark, Licensor covenants to MariaDB, and to all +other recipients of the licensed work to be provided by Licensor: + +1. To specify as the Change License the GPL Version 2.0 or any later version, + or a license that is compatible with GPL Version 2.0 or a later version, + where “compatible” means that software provided under the Change License can + be included in a program with software provided under GPL Version 2.0 or a + later version. Licensor may specify additional Change Licenses without + limitation. + +2. To either: (a) specify an additional grant of rights to use that does not + impose any additional restriction on the right granted in this License, as + the Additional Use Grant; or (b) insert the text “None”. + +3. To specify a Change Date. + +4. Not to modify this License in any other way. + +----------------------------------------------------------------------------- + +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License, version 3, as published +by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License +along with this program; if not, see . + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission to convey the resulting work. + +Additional permission under GNU AGPL version 3 section 13 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission that, notwithstanding any other provision of this +License, you need not prominently offer all users interacting with your +modified version remotely through a computer network an opportunity to +receive the Corresponding Source of your version from a network server at no +charge, if your version supports such interaction. This permission does not +waive or modify any other obligations or terms of the AGPL v3.0, except for +the specific requirement set forth in section 13. + +A copy of the AGPL v3.0 license is reproduced below. + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs, and that you know you can +do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the +software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free +software are heartened and encouraged by the resulting cooperation. However, +in the case of software used on network servers, this result may fail to come +about. The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its source +code to the public. + +The GNU Affero General Public License is designed specifically to ensure +that, in such cases, the modified source code becomes available to the +community. It requires the operator of a network server to provide the source +code of the modified version running there to the users of that server. +Therefore, public use of a modified version, on a publicly accessible server, +gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different +license, not a version of the Affero GPL, but Affero has released a new +version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be +individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a +fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under +applicable copyright law, except executing it on a computer or modifying a +private copy. Propagation includes copying, distribution (with or without +modification), making available to the public, and in some countries other +activities as well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that (1) +displays an appropriate copyright notice, and (2) tells the user that there +is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how to +view a copy of this License. If the interface presents a list of user +commands or options, such as a menu, a prominent item in the list meets this +criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces +specified for a particular programming language, one that is widely used +among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the +work as a whole, that (a) is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and (b) serves only +to enable use of the work with that Major Component, or to implement a +Standard Interface for which an implementation is available to the public in +source code form. A "Major Component", in this context, means a major +essential component (kernel, window system, and so on) of the specific +operating system (if any) on which the executable work runs, or a compiler +used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the +source code needed to generate, install, and (for an executable work) run the +object code and to modify the work, including scripts to control those +activities. However, it does not include the work's System Libraries, or +general-purpose tools or generally available free programs which are used +unmodified in performing those activities but which are not part of the work. +For example, Corresponding Source includes interface definition files +associated with source files for the work, and the source code for shared +libraries and dynamically linked subprograms that the work is specifically +designed to require, such as by intimate data communication or control flow +between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the +unmodified Program. The output from running a covered work is covered by this +License only if the output, given its content, constitutes a covered work. +This License acknowledges your rights of fair use or other equivalent, as +provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make +modifications exclusively for you, or provide you with facilities for running +those works, provided that you comply with the terms of this License in +conveying all material for which you do not control copyright. Those thus +making or running the covered works for you must do so exclusively on your +behalf, under your direction and control, on terms that prohibit them from +making any copies of your copyrighted material outside their relationship +with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes it +unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention is +effected by exercising rights under this License with respect to the covered +work, and you disclaim any intention to limit operation or modification of +the work as a means of enforcing, against the work's users, your or third +parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section 7 +apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section 4, +provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement +modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, and +all its parts, regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do not +display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of a +storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to the +other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by a written offer, valid for at +least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium +customarily used for software interchange, for a price no more than your +reasonable cost of physically performing this conveying of source, or (2) +access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source in +the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the +Corresponding Source may be on a different server (operated by you or a third +party) that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the Corresponding +Source, you remain obligated to ensure that it is available for as long as +needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you +inform other peers where the object code and Corresponding Source of the work +are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in +conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a +particular user, "normally used" refers to a typical or common use of that +class of product, regardless of the status of the particular user or of the +way in which the particular user actually uses, or expects or is expected to +use, the product. A product is a consumer product regardless of whether the +product has substantial commercial, industrial or non-consumer uses, unless +such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified +version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case +prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part of +a transaction in which the right of possession and use of the User Product is +transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed +under this section must be accompanied by the Installation Information. But +this requirement does not apply if neither you nor any third party retains +the ability to install modified object code on the User Product (for example, +the work has been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates for +a work that has been modified or installed by the recipient, or for the User +Product in which it has been modified or installed. Access to a network may +be denied when the modification itself materially and adversely affects the +operation of the network or violates the rules and protocols for +communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in +accord with this section must be in a format that is publicly documented (and +with an implementation available to the public in source code form), and must +require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional +permissions that are applicable to the entire Program shall be treated as +though they were included in this License, to the extent that they are valid +under applicable law. If additional permissions apply only to part of the +Program, that part may be used separately under those permissions, but the +entire Program remains governed by this License without regard to the +additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate +copyright permission. + +Notwithstanding any other provision of this License, for material you add to +a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as +different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these +contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is governed +by this License along with a term that is a further restriction, you may +remove that term. If a license document contains a further restriction but +permits relicensing or conveying under this License, you may add to a covered +work material governed by the terms of that license document, provided that +the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must +place, in the relevant source files, a statement of the additional terms that +apply to those files, or a notice indicating where to find the applicable +terms. + +Additional terms, permissive or non-permissive, may be stated in the form of +a separately written license, or stated as exceptions; the above requirements +apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated (a) provisionally, unless and until +the copyright holder explicitly and finally terminates your license, and (b) +permanently, if the copyright holder fails to notify you of the violation by +some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by some +reasonable means, this is the first time you have received notice of +violation of this License (for any work) from that copyright holder, and you +cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. If +your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as a +consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions +infringe copyright if you do not accept this License. Therefore, by modifying +or propagating a covered work, you indicate your acceptance of this License +to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a +license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance by +third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who +receives a copy of the work also receives whatever licenses to the work the +party's predecessor in interest had or could give under the previous +paragraph, plus a right to possession of the Corresponding Source of the work +from the predecessor in interest, if the predecessor has it or can get it +with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim or +counterclaim in a lawsuit) alleging that any patent claim is infringed by +making, using, selling, offering for sale, or importing the Program or any +portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus +licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter +acquired, that would be infringed by some manner, permitted by this License, +of making, using, or selling its contributor version, but do not include +claims that would be infringed only as a consequence of further modification +of the contributor version. For purposes of this definition, "control" +includes the right to grant patent sublicenses in a manner consistent with +the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent (such +as an express permission to practice a patent or covenant not to sue for +patent infringement). To "grant" such a patent license to a party means to +make such an agreement or commitment not to enforce a patent against the +party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of +charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, to +extend the patent license to downstream recipients. "Knowingly relying" means +you have actual knowledge that, but for the patent license, your conveying +the covered work in a country, or your recipient's use of the covered work in +a country, would infringe one or more identifiable patents in that country +that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and +grant a patent license to some of the parties receiving the covered work +authorizing them to use, propagate, modify or convey a specific copy of the +covered work, then the patent license you grant is automatically extended to +all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the +non-exercise of one or more of the rights that are specifically granted under +this License. You may not convey a covered work if you are a party to an +arrangement with a third party that is in the business of distributing +software, under which you make payment to the third party based on the extent +of your activity of conveying the work, and under which the third party +grants, to any of the parties who would receive the covered work from you, a +discriminatory patent license (a) in connection with copies of the covered +work conveyed by you (or copies made from those copies), or (b) primarily for +and in connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any +implied license or other defenses to infringement that may otherwise be +available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not excuse +you from the conditions of this License. If you cannot convey a covered work +so as to satisfy simultaneously your obligations under this License and any +other pertinent obligations, then as a consequence you may not convey it at +all. For example, if you agree to terms that obligate you to collect a +royalty for further conveying from those to whom you convey the Program, the +only way you could satisfy both those terms and this License would be to +refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users interacting +with it remotely through a computer network (if your version supports such +interaction) an opportunity to receive the Corresponding Source of your +version by providing access to the Corresponding Source from a network server +at no charge, through some standard or customary means of facilitating +copying of software. This Corresponding Source shall include the +Corresponding Source for any work covered by version 3 of the GNU General +Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or of any +later version published by the Free Software Foundation. If the Program does +not specify a version number of the GNU Affero General Public License, you +may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the +GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or copyright +holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. +SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY +SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE +OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR +DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR +A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above +cannot be given local legal effect according to their terms, reviewing courts +shall apply local law that most closely approximates an absolute waiver of +all civil liability in connection with the Program, unless a warranty or +assumption of liability accompanies a copy of the Program in return for a +fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + +SpacetimeDB: A database which replaces your server. +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could +display a "Source" link that leads users to an archive of the code. There are +many ways you could offer source, and different solutions will be better for +different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if +any, to sign a "copyright disclaimer" for the program, if necessary. For more +information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/spacetime-crypto-ts/README.md b/spacetime-crypto-ts/README.md new file mode 100644 index 00000000000..f6a7dc2d516 --- /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 + +BUSL-1.1. 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..04c4900a497 --- /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": "BUSL-1.1", + "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..cabc15d1ee3 --- /dev/null +++ b/spacetime-crypto-ts/scripts/test-vectors.ts @@ -0,0 +1,340 @@ +// Verify the pure-TS implementations against published 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..a0dae825856 --- /dev/null +++ b/spacetime-crypto-ts/src/timing.ts @@ -0,0 +1,111 @@ +/** + * 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; +} + +/** Decode `01ab23cd` into Uint8Array. Throws on odd length or non-hex. */ +export function hexToBytes(hex: string): Uint8Array { + if (hex.length % 2 !== 0) throw new Error('hex: odd length'); + const out = new Uint8Array(hex.length / 2); + for (let i = 0; i < out.length; i++) { + const hi = hexNibble(hex.charCodeAt(i * 2)); + const lo = hexNibble(hex.charCodeAt(i * 2 + 1)); + out[i] = (hi << 4) | lo; + } + return out; +} + +function hexNibble(code: number): number { + if (code >= 0x30 && code <= 0x39) return code - 0x30; + if (code >= 0x61 && code <= 0x66) return code - 0x61 + 10; + if (code >= 0x41 && code <= 0x46) return code - 0x41 + 10; + throw new Error(`hex: non-hex char ${String.fromCharCode(code)}`); +} + +/** Encode bytes as lowercase hex. */ +export function bytesToHex(bytes: Uint8Array): string { + let s = ''; + for (let i = 0; i < bytes.length; i++) { + s += bytes[i].toString(16).padStart(2, '0'); + } + return s; +} + +/** 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..ea0cb1c5e9e --- /dev/null +++ b/spacetime-rate-limit-ts/LICENSE.txt @@ -0,0 +1,759 @@ +SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT + +Business Source License 1.1 + +Parameters + +Licensor: Clockwork Laboratories, Inc. +Licensed Work: SpacetimeDB 2.8.3 + The Licensed Work is + (c) 2023 Clockwork Laboratories, Inc. + +Additional Use Grant: You may make use of the Licensed Work provided your + application or service uses the Licensed Work with no + more than one SpacetimeDB instance in production and + provided that you do not use the Licensed Work for a + Database Service. + + A “Database Service” is a commercial offering that + allows third parties (other than your employees and + contractors) to access the functionality of the + Licensed Work by creating tables whose schemas are + controlled by such third parties. + +Change Date: 2031-08-18 + +Change License: GNU Affero General Public License v3.0 with a linking + exception + +For information about alternative licensing arrangements for the Software, +please visit: https://spacetimedb.com + +Notice + +The Business Source License (this document, or the “License”) is not an Open +Source license. However, the Licensed Work will eventually be made available +under an Open Source License, as stated in this License. + +License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. +“Business Source License” is a trademark of MariaDB Corporation Ab. + +----------------------------------------------------------------------------- + +Base License and Subdirectory Specific Licenses + +1. Repository-Wide License +Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. + +2. Subdirectory-Specific Licenses +Certain subdirectories within this repository are licensed under different terms. + +If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. + +In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. + +3. Contributor Acknowledgement +By contributing to this repository, you agree that: + +Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. + +If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. + +4. Reading the Applicable License +Before using, modifying, or distributing code from this repository, you must read: + +This base LICENSE.txt file for the overall repository license. + +Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. + +----------------------------------------------------------------------------- + +Business Source License 1.1 + +Terms + +The Licensor hereby grants you the right to copy, modify, create derivative +works, redistribute, and make non-production use of the Licensed Work. The +Licensor may make an Additional Use Grant, above, permitting limited +production use. + +Effective on the Change Date, or the fourth anniversary of the first publicly +available distribution of a specific version of the Licensed Work under this +License, whichever comes first, the Licensor hereby grants you rights under +the terms of the Change License, and the rights granted in the paragraph +above terminate. + +If your use of the Licensed Work does not comply with the requirements +currently in effect as described in this License, you must purchase a +commercial license from the Licensor, its affiliated entities, or authorized +resellers, or you must refrain from using the Licensed Work. + +All copies of the original and modified Licensed Work, and derivative works +of the Licensed Work, are subject to this License. This License applies +separately for each version of the Licensed Work and the Change Date may vary +for each version of the Licensed Work released by Licensor. + +You must conspicuously display this License on each original or modified copy +of the Licensed Work. If you receive the Licensed Work in original or +modified form from a third party, the terms and conditions set forth in this +License apply to your use of that work. + +Any use of the Licensed Work in violation of this License will automatically +terminate your rights under this License for the current and all other +versions of the Licensed Work. + +This License does not grant you any right in any trademark or logo of +Licensor or its affiliates (provided that you may use a trademark or logo of +Licensor as expressly required by this License). + +TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON +AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, +EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND +TITLE. + +MariaDB hereby grants you permission to use this License’s text to license +your works, and to refer to it using the trademark “Business Source License”, +as long as you comply with the Covenants of Licensor below. + +Covenants of Licensor + +In consideration of the right to use this License’s text and the “Business +Source License” name and trademark, Licensor covenants to MariaDB, and to all +other recipients of the licensed work to be provided by Licensor: + +1. To specify as the Change License the GPL Version 2.0 or any later version, + or a license that is compatible with GPL Version 2.0 or a later version, + where “compatible” means that software provided under the Change License can + be included in a program with software provided under GPL Version 2.0 or a + later version. Licensor may specify additional Change Licenses without + limitation. + +2. To either: (a) specify an additional grant of rights to use that does not + impose any additional restriction on the right granted in this License, as + the Additional Use Grant; or (b) insert the text “None”. + +3. To specify a Change Date. + +4. Not to modify this License in any other way. + +----------------------------------------------------------------------------- + +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License, version 3, as published +by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License +along with this program; if not, see . + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission to convey the resulting work. + +Additional permission under GNU AGPL version 3 section 13 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission that, notwithstanding any other provision of this +License, you need not prominently offer all users interacting with your +modified version remotely through a computer network an opportunity to +receive the Corresponding Source of your version from a network server at no +charge, if your version supports such interaction. This permission does not +waive or modify any other obligations or terms of the AGPL v3.0, except for +the specific requirement set forth in section 13. + +A copy of the AGPL v3.0 license is reproduced below. + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs, and that you know you can +do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the +software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free +software are heartened and encouraged by the resulting cooperation. However, +in the case of software used on network servers, this result may fail to come +about. The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its source +code to the public. + +The GNU Affero General Public License is designed specifically to ensure +that, in such cases, the modified source code becomes available to the +community. It requires the operator of a network server to provide the source +code of the modified version running there to the users of that server. +Therefore, public use of a modified version, on a publicly accessible server, +gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different +license, not a version of the Affero GPL, but Affero has released a new +version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be +individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a +fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under +applicable copyright law, except executing it on a computer or modifying a +private copy. Propagation includes copying, distribution (with or without +modification), making available to the public, and in some countries other +activities as well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that (1) +displays an appropriate copyright notice, and (2) tells the user that there +is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how to +view a copy of this License. If the interface presents a list of user +commands or options, such as a menu, a prominent item in the list meets this +criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces +specified for a particular programming language, one that is widely used +among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the +work as a whole, that (a) is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and (b) serves only +to enable use of the work with that Major Component, or to implement a +Standard Interface for which an implementation is available to the public in +source code form. A "Major Component", in this context, means a major +essential component (kernel, window system, and so on) of the specific +operating system (if any) on which the executable work runs, or a compiler +used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the +source code needed to generate, install, and (for an executable work) run the +object code and to modify the work, including scripts to control those +activities. However, it does not include the work's System Libraries, or +general-purpose tools or generally available free programs which are used +unmodified in performing those activities but which are not part of the work. +For example, Corresponding Source includes interface definition files +associated with source files for the work, and the source code for shared +libraries and dynamically linked subprograms that the work is specifically +designed to require, such as by intimate data communication or control flow +between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the +unmodified Program. The output from running a covered work is covered by this +License only if the output, given its content, constitutes a covered work. +This License acknowledges your rights of fair use or other equivalent, as +provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make +modifications exclusively for you, or provide you with facilities for running +those works, provided that you comply with the terms of this License in +conveying all material for which you do not control copyright. Those thus +making or running the covered works for you must do so exclusively on your +behalf, under your direction and control, on terms that prohibit them from +making any copies of your copyrighted material outside their relationship +with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes it +unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention is +effected by exercising rights under this License with respect to the covered +work, and you disclaim any intention to limit operation or modification of +the work as a means of enforcing, against the work's users, your or third +parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section 7 +apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section 4, +provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement +modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, and +all its parts, regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do not +display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of a +storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to the +other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by a written offer, valid for at +least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium +customarily used for software interchange, for a price no more than your +reasonable cost of physically performing this conveying of source, or (2) +access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source in +the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the +Corresponding Source may be on a different server (operated by you or a third +party) that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the Corresponding +Source, you remain obligated to ensure that it is available for as long as +needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you +inform other peers where the object code and Corresponding Source of the work +are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in +conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a +particular user, "normally used" refers to a typical or common use of that +class of product, regardless of the status of the particular user or of the +way in which the particular user actually uses, or expects or is expected to +use, the product. A product is a consumer product regardless of whether the +product has substantial commercial, industrial or non-consumer uses, unless +such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified +version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case +prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part of +a transaction in which the right of possession and use of the User Product is +transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed +under this section must be accompanied by the Installation Information. But +this requirement does not apply if neither you nor any third party retains +the ability to install modified object code on the User Product (for example, +the work has been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates for +a work that has been modified or installed by the recipient, or for the User +Product in which it has been modified or installed. Access to a network may +be denied when the modification itself materially and adversely affects the +operation of the network or violates the rules and protocols for +communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in +accord with this section must be in a format that is publicly documented (and +with an implementation available to the public in source code form), and must +require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional +permissions that are applicable to the entire Program shall be treated as +though they were included in this License, to the extent that they are valid +under applicable law. If additional permissions apply only to part of the +Program, that part may be used separately under those permissions, but the +entire Program remains governed by this License without regard to the +additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate +copyright permission. + +Notwithstanding any other provision of this License, for material you add to +a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as +different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these +contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is governed +by this License along with a term that is a further restriction, you may +remove that term. If a license document contains a further restriction but +permits relicensing or conveying under this License, you may add to a covered +work material governed by the terms of that license document, provided that +the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must +place, in the relevant source files, a statement of the additional terms that +apply to those files, or a notice indicating where to find the applicable +terms. + +Additional terms, permissive or non-permissive, may be stated in the form of +a separately written license, or stated as exceptions; the above requirements +apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated (a) provisionally, unless and until +the copyright holder explicitly and finally terminates your license, and (b) +permanently, if the copyright holder fails to notify you of the violation by +some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by some +reasonable means, this is the first time you have received notice of +violation of this License (for any work) from that copyright holder, and you +cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. If +your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as a +consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions +infringe copyright if you do not accept this License. Therefore, by modifying +or propagating a covered work, you indicate your acceptance of this License +to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a +license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance by +third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who +receives a copy of the work also receives whatever licenses to the work the +party's predecessor in interest had or could give under the previous +paragraph, plus a right to possession of the Corresponding Source of the work +from the predecessor in interest, if the predecessor has it or can get it +with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim or +counterclaim in a lawsuit) alleging that any patent claim is infringed by +making, using, selling, offering for sale, or importing the Program or any +portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus +licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter +acquired, that would be infringed by some manner, permitted by this License, +of making, using, or selling its contributor version, but do not include +claims that would be infringed only as a consequence of further modification +of the contributor version. For purposes of this definition, "control" +includes the right to grant patent sublicenses in a manner consistent with +the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent (such +as an express permission to practice a patent or covenant not to sue for +patent infringement). To "grant" such a patent license to a party means to +make such an agreement or commitment not to enforce a patent against the +party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of +charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, to +extend the patent license to downstream recipients. "Knowingly relying" means +you have actual knowledge that, but for the patent license, your conveying +the covered work in a country, or your recipient's use of the covered work in +a country, would infringe one or more identifiable patents in that country +that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and +grant a patent license to some of the parties receiving the covered work +authorizing them to use, propagate, modify or convey a specific copy of the +covered work, then the patent license you grant is automatically extended to +all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the +non-exercise of one or more of the rights that are specifically granted under +this License. You may not convey a covered work if you are a party to an +arrangement with a third party that is in the business of distributing +software, under which you make payment to the third party based on the extent +of your activity of conveying the work, and under which the third party +grants, to any of the parties who would receive the covered work from you, a +discriminatory patent license (a) in connection with copies of the covered +work conveyed by you (or copies made from those copies), or (b) primarily for +and in connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any +implied license or other defenses to infringement that may otherwise be +available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not excuse +you from the conditions of this License. If you cannot convey a covered work +so as to satisfy simultaneously your obligations under this License and any +other pertinent obligations, then as a consequence you may not convey it at +all. For example, if you agree to terms that obligate you to collect a +royalty for further conveying from those to whom you convey the Program, the +only way you could satisfy both those terms and this License would be to +refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users interacting +with it remotely through a computer network (if your version supports such +interaction) an opportunity to receive the Corresponding Source of your +version by providing access to the Corresponding Source from a network server +at no charge, through some standard or customary means of facilitating +copying of software. This Corresponding Source shall include the +Corresponding Source for any work covered by version 3 of the GNU General +Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or of any +later version published by the Free Software Foundation. If the Program does +not specify a version number of the GNU Affero General Public License, you +may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the +GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or copyright +holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. +SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY +SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE +OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR +DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR +A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above +cannot be given local legal effect according to their terms, reviewing courts +shall apply local law that most closely approximates an absolute waiver of +all civil liability in connection with the Program, unless a warranty or +assumption of liability accompanies a copy of the Program in return for a +fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + +SpacetimeDB: A database which replaces your server. +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could +display a "Source" link that leads users to an archive of the code. There are +many ways you could offer source, and different solutions will be better for +different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if +any, to sign a "copyright disclaimer" for the program, if necessary. For more +information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md new file mode 100644 index 00000000000..5fa33c4dfd9 --- /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@^2.8.3 +``` + +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 + +[BUSL-1.1](./LICENSE.txt) - same as SpacetimeDB. 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..0701813bd2c --- /dev/null +++ b/spacetime-rate-limit-ts/example/README.md @@ -0,0 +1,178 @@ +# 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. +- The released SpacetimeDB 2.8 CLI. +- A local SpacetimeDB server registered as `local`. +- A logged-in CLI identity for publishing and optional admin grants. + +Select the supported CLI release, then keep the local server running in a +separate terminal: + +```powershell +spacetime version install 2.8.3 +spacetime version use 2.8.3 +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@^2.8.3 +``` + +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..06e1d241db6 --- /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 start_reactor = 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 tap_reactor = 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 buy_upgrade = 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 repair_reactor = 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 set_player_color = 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 rate_limit_demo_sweep = 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..e7b95496647 --- /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.8.3 (commit 8e410d2842147bd8e5a32a9589cc00c19f7478e2). + +/* 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.8.3" 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..c828b291e19 --- /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": "BUSL-1.1", + "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..c11828b0c59 --- /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, + rate_limit_sweep, + 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..d7a2c306a72 --- /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, + rate_limit_sweep, + 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..bda705dcaad --- /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 rate_limit_sweep = 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..ea0cb1c5e9e --- /dev/null +++ b/spacetime-retry-ts/LICENSE.txt @@ -0,0 +1,759 @@ +SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT + +Business Source License 1.1 + +Parameters + +Licensor: Clockwork Laboratories, Inc. +Licensed Work: SpacetimeDB 2.8.3 + The Licensed Work is + (c) 2023 Clockwork Laboratories, Inc. + +Additional Use Grant: You may make use of the Licensed Work provided your + application or service uses the Licensed Work with no + more than one SpacetimeDB instance in production and + provided that you do not use the Licensed Work for a + Database Service. + + A “Database Service” is a commercial offering that + allows third parties (other than your employees and + contractors) to access the functionality of the + Licensed Work by creating tables whose schemas are + controlled by such third parties. + +Change Date: 2031-08-18 + +Change License: GNU Affero General Public License v3.0 with a linking + exception + +For information about alternative licensing arrangements for the Software, +please visit: https://spacetimedb.com + +Notice + +The Business Source License (this document, or the “License”) is not an Open +Source license. However, the Licensed Work will eventually be made available +under an Open Source License, as stated in this License. + +License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. +“Business Source License” is a trademark of MariaDB Corporation Ab. + +----------------------------------------------------------------------------- + +Base License and Subdirectory Specific Licenses + +1. Repository-Wide License +Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. + +2. Subdirectory-Specific Licenses +Certain subdirectories within this repository are licensed under different terms. + +If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. + +In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. + +3. Contributor Acknowledgement +By contributing to this repository, you agree that: + +Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. + +If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. + +4. Reading the Applicable License +Before using, modifying, or distributing code from this repository, you must read: + +This base LICENSE.txt file for the overall repository license. + +Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. + +----------------------------------------------------------------------------- + +Business Source License 1.1 + +Terms + +The Licensor hereby grants you the right to copy, modify, create derivative +works, redistribute, and make non-production use of the Licensed Work. The +Licensor may make an Additional Use Grant, above, permitting limited +production use. + +Effective on the Change Date, or the fourth anniversary of the first publicly +available distribution of a specific version of the Licensed Work under this +License, whichever comes first, the Licensor hereby grants you rights under +the terms of the Change License, and the rights granted in the paragraph +above terminate. + +If your use of the Licensed Work does not comply with the requirements +currently in effect as described in this License, you must purchase a +commercial license from the Licensor, its affiliated entities, or authorized +resellers, or you must refrain from using the Licensed Work. + +All copies of the original and modified Licensed Work, and derivative works +of the Licensed Work, are subject to this License. This License applies +separately for each version of the Licensed Work and the Change Date may vary +for each version of the Licensed Work released by Licensor. + +You must conspicuously display this License on each original or modified copy +of the Licensed Work. If you receive the Licensed Work in original or +modified form from a third party, the terms and conditions set forth in this +License apply to your use of that work. + +Any use of the Licensed Work in violation of this License will automatically +terminate your rights under this License for the current and all other +versions of the Licensed Work. + +This License does not grant you any right in any trademark or logo of +Licensor or its affiliates (provided that you may use a trademark or logo of +Licensor as expressly required by this License). + +TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON +AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, +EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND +TITLE. + +MariaDB hereby grants you permission to use this License’s text to license +your works, and to refer to it using the trademark “Business Source License”, +as long as you comply with the Covenants of Licensor below. + +Covenants of Licensor + +In consideration of the right to use this License’s text and the “Business +Source License” name and trademark, Licensor covenants to MariaDB, and to all +other recipients of the licensed work to be provided by Licensor: + +1. To specify as the Change License the GPL Version 2.0 or any later version, + or a license that is compatible with GPL Version 2.0 or a later version, + where “compatible” means that software provided under the Change License can + be included in a program with software provided under GPL Version 2.0 or a + later version. Licensor may specify additional Change Licenses without + limitation. + +2. To either: (a) specify an additional grant of rights to use that does not + impose any additional restriction on the right granted in this License, as + the Additional Use Grant; or (b) insert the text “None”. + +3. To specify a Change Date. + +4. Not to modify this License in any other way. + +----------------------------------------------------------------------------- + +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License, version 3, as published +by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License +along with this program; if not, see . + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission to convey the resulting work. + +Additional permission under GNU AGPL version 3 section 13 + +If you modify this Program, or any covered work, by linking or combining it +with SpacetimeDB (or a modified version of that library), containing parts +covered by the terms of the AGPL v3.0, the licensors of this Program grant +you additional permission that, notwithstanding any other provision of this +License, you need not prominently offer all users interacting with your +modified version remotely through a computer network an opportunity to +receive the Corresponding Source of your version from a network server at no +charge, if your version supports such interaction. This permission does not +waive or modify any other obligations or terms of the AGPL v3.0, except for +the specific requirement set forth in section 13. + +A copy of the AGPL v3.0 license is reproduced below. + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright © 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs, and that you know you can +do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the +software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free +software are heartened and encouraged by the resulting cooperation. However, +in the case of software used on network servers, this result may fail to come +about. The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its source +code to the public. + +The GNU Affero General Public License is designed specifically to ensure +that, in such cases, the modified source code becomes available to the +community. It requires the operator of a network server to provide the source +code of the modified version running there to the users of that server. +Therefore, public use of a modified version, on a publicly accessible server, +gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different +license, not a version of the Affero GPL, but Affero has released a new +version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS +0. Definitions. +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be +individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a +fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under +applicable copyright law, except executing it on a computer or modifying a +private copy. Propagation includes copying, distribution (with or without +modification), making available to the public, and in some countries other +activities as well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that (1) +displays an appropriate copyright notice, and (2) tells the user that there +is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how to +view a copy of this License. If the interface presents a list of user +commands or options, such as a menu, a prominent item in the list meets this +criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces +specified for a particular programming language, one that is widely used +among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the +work as a whole, that (a) is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and (b) serves only +to enable use of the work with that Major Component, or to implement a +Standard Interface for which an implementation is available to the public in +source code form. A "Major Component", in this context, means a major +essential component (kernel, window system, and so on) of the specific +operating system (if any) on which the executable work runs, or a compiler +used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the +source code needed to generate, install, and (for an executable work) run the +object code and to modify the work, including scripts to control those +activities. However, it does not include the work's System Libraries, or +general-purpose tools or generally available free programs which are used +unmodified in performing those activities but which are not part of the work. +For example, Corresponding Source includes interface definition files +associated with source files for the work, and the source code for shared +libraries and dynamically linked subprograms that the work is specifically +designed to require, such as by intimate data communication or control flow +between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the +unmodified Program. The output from running a covered work is covered by this +License only if the output, given its content, constitutes a covered work. +This License acknowledges your rights of fair use or other equivalent, as +provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make +modifications exclusively for you, or provide you with facilities for running +those works, provided that you comply with the terms of this License in +conveying all material for which you do not control copyright. Those thus +making or running the covered works for you must do so exclusively on your +behalf, under your direction and control, on terms that prohibit them from +making any copies of your copyrighted material outside their relationship +with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes it +unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention is +effected by exercising rights under this License with respect to the covered +work, and you disclaim any intention to limit operation or modification of +the work as a means of enforcing, against the work's users, your or third +parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section 7 +apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section 4, +provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement +modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, and +all its parts, regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do not +display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of a +storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to the +other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by a written offer, valid for at +least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium +customarily used for software interchange, for a price no more than your +reasonable cost of physically performing this conveying of source, or (2) +access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source in +the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the +Corresponding Source may be on a different server (operated by you or a third +party) that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the Corresponding +Source, you remain obligated to ensure that it is available for as long as +needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you +inform other peers where the object code and Corresponding Source of the work +are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in +conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a +particular user, "normally used" refers to a typical or common use of that +class of product, regardless of the status of the particular user or of the +way in which the particular user actually uses, or expects or is expected to +use, the product. A product is a consumer product regardless of whether the +product has substantial commercial, industrial or non-consumer uses, unless +such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified +version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case +prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part of +a transaction in which the right of possession and use of the User Product is +transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed +under this section must be accompanied by the Installation Information. But +this requirement does not apply if neither you nor any third party retains +the ability to install modified object code on the User Product (for example, +the work has been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates for +a work that has been modified or installed by the recipient, or for the User +Product in which it has been modified or installed. Access to a network may +be denied when the modification itself materially and adversely affects the +operation of the network or violates the rules and protocols for +communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in +accord with this section must be in a format that is publicly documented (and +with an implementation available to the public in source code form), and must +require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional +permissions that are applicable to the entire Program shall be treated as +though they were included in this License, to the extent that they are valid +under applicable law. If additional permissions apply only to part of the +Program, that part may be used separately under those permissions, but the +entire Program remains governed by this License without regard to the +additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate +copyright permission. + +Notwithstanding any other provision of this License, for material you add to +a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as +different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these +contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is governed +by this License along with a term that is a further restriction, you may +remove that term. If a license document contains a further restriction but +permits relicensing or conveying under this License, you may add to a covered +work material governed by the terms of that license document, provided that +the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must +place, in the relevant source files, a statement of the additional terms that +apply to those files, or a notice indicating where to find the applicable +terms. + +Additional terms, permissive or non-permissive, may be stated in the form of +a separately written license, or stated as exceptions; the above requirements +apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated (a) provisionally, unless and until +the copyright holder explicitly and finally terminates your license, and (b) +permanently, if the copyright holder fails to notify you of the violation by +some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by some +reasonable means, this is the first time you have received notice of +violation of this License (for any work) from that copyright holder, and you +cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. If +your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as a +consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions +infringe copyright if you do not accept this License. Therefore, by modifying +or propagating a covered work, you indicate your acceptance of this License +to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a +license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance by +third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who +receives a copy of the work also receives whatever licenses to the work the +party's predecessor in interest had or could give under the previous +paragraph, plus a right to possession of the Corresponding Source of the work +from the predecessor in interest, if the predecessor has it or can get it +with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim or +counterclaim in a lawsuit) alleging that any patent claim is infringed by +making, using, selling, offering for sale, or importing the Program or any +portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus +licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter +acquired, that would be infringed by some manner, permitted by this License, +of making, using, or selling its contributor version, but do not include +claims that would be infringed only as a consequence of further modification +of the contributor version. For purposes of this definition, "control" +includes the right to grant patent sublicenses in a manner consistent with +the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent (such +as an express permission to practice a patent or covenant not to sue for +patent infringement). To "grant" such a patent license to a party means to +make such an agreement or commitment not to enforce a patent against the +party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of +charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, to +extend the patent license to downstream recipients. "Knowingly relying" means +you have actual knowledge that, but for the patent license, your conveying +the covered work in a country, or your recipient's use of the covered work in +a country, would infringe one or more identifiable patents in that country +that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and +grant a patent license to some of the parties receiving the covered work +authorizing them to use, propagate, modify or convey a specific copy of the +covered work, then the patent license you grant is automatically extended to +all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the +non-exercise of one or more of the rights that are specifically granted under +this License. You may not convey a covered work if you are a party to an +arrangement with a third party that is in the business of distributing +software, under which you make payment to the third party based on the extent +of your activity of conveying the work, and under which the third party +grants, to any of the parties who would receive the covered work from you, a +discriminatory patent license (a) in connection with copies of the covered +work conveyed by you (or copies made from those copies), or (b) primarily for +and in connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any +implied license or other defenses to infringement that may otherwise be +available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not excuse +you from the conditions of this License. If you cannot convey a covered work +so as to satisfy simultaneously your obligations under this License and any +other pertinent obligations, then as a consequence you may not convey it at +all. For example, if you agree to terms that obligate you to collect a +royalty for further conveying from those to whom you convey the Program, the +only way you could satisfy both those terms and this License would be to +refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users interacting +with it remotely through a computer network (if your version supports such +interaction) an opportunity to receive the Corresponding Source of your +version by providing access to the Corresponding Source from a network server +at no charge, through some standard or customary means of facilitating +copying of software. This Corresponding Source shall include the +Corresponding Source for any work covered by version 3 of the GNU General +Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or of any +later version published by the Free Software Foundation. If the Program does +not specify a version number of the GNU Affero General Public License, you +may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the +GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or copyright +holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. +SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY +SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE +OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR +DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR +A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above +cannot be given local legal effect according to their terms, reviewing courts +shall apply local law that most closely approximates an absolute waiver of +all civil liability in connection with the Program, unless a warranty or +assumption of liability accompanies a copy of the Program in return for a +fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + +SpacetimeDB: A database which replaces your server. +Copyright (C) 2023 Clockwork Laboratories, Inc. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could +display a "Source" link that leads users to an archive of the code. There are +many ways you could offer source, and different solutions will be better for +different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if +any, to sign a "copyright disclaimer" for the program, if necessary. For more +information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md new file mode 100644 index 00000000000..abfab976ec9 --- /dev/null +++ b/spacetime-retry-ts/README.md @@ -0,0 +1,120 @@ +# @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@^2.8.3 +``` + +Requires SpacetimeDB 2.8.3 or later for submodule mounting. + +`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. Keep the registration casts at this SDK/factory +boundary; application code stays typed through the handler map. + +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 }, + { + send_receipt: 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 }); +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`. + +## 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: 'send_receipt', 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 handler, dispatch, and result helpers. + +The complete factory is available from `./submodule`. + +## Testing + +```bash +pnpm test +pnpm run lint +pnpm run build +``` + +The repository build compiles the local fixture module that mounts the factory. + +## License + +BUSL-1.1. 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..e37077d8579 --- /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": "BUSL-1.1", + "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..d6622d58feb --- /dev/null +++ b/spacetime-retry-ts/scripts/test.ts @@ -0,0 +1,45 @@ +import * as assert from 'node:assert/strict'; +import type { AlgebraicType } from 'spacetimedb'; +import type { TypeBuilder } from 'spacetimedb/server'; +import { + makeRetryDispatch, + retryFailed, + retryHandler, + retryOk, +} from '../src/handler.ts'; + +const fakeBuilder = (): TypeBuilder => + ({}) as unknown as TypeBuilder; + +const calls: string[] = []; +const handlers = { + noArgs: retryHandler(fakeBuilder>(), () => { + calls.push('noArgs'); + return retryOk(); + }), + withArgs: retryHandler( + fakeBuilder<{ value: 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/ +); + +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..a6848e82684 --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/src/index.ts @@ -0,0 +1,114 @@ +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(), +}); + +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) { + return retryFailed(`simulated failure at attempt ${attempt}`); + } + 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 retry_fire = spacetimedb.reducer( + { onSchedule: retryTask }, + { arg: retryTask.rowType }, + retry.reducers.retryFire +); + +export const submit_retry_task = spacetimedb.reducer( + retry.reducers.submitRetryTask.params, + retry.reducers.submitRetryTask.handler +); + +export const add_retry_admin_identity = spacetimedb.reducer( + retry.reducers.addRetryAdminIdentity.params, + retry.reducers.addRetryAdminIdentity.handler +); + +export const remove_retry_admin_identity = 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..0d376bc61f8 --- /dev/null +++ b/spacetime-retry-ts/src/handler.ts @@ -0,0 +1,54 @@ +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 { + const handler = (handlers as Record)[args.tag]; + if (!handler) throw new Error(`unknown retry handler: ${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..2be1873e4aa --- /dev/null +++ b/spacetime-retry-ts/src/submodule.ts @@ -0,0 +1,329 @@ +import { makeRetryDispatch, type RetryHandler } 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; + +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 }; + 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) ? takeRows(retryCtx.db.retryHistory.iter()) : []; + } + + 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, + }); + + const result = dispatchRetry( + retryCtx, + arg.args as RetryDispatchArg & { + tag: keyof H & string; + } + ); + + 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"] +} From e0f5d86fc563d7271006762a1eed6a7f9a01ac8f Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 9 Sep 2026 14:26:44 -0400 Subject: [PATCH 02/32] Reuse noble hex conversion helpers --- spacetime-crypto-ts/src/timing.ts | 28 +--------------------------- 1 file changed, 1 insertion(+), 27 deletions(-) diff --git a/spacetime-crypto-ts/src/timing.ts b/spacetime-crypto-ts/src/timing.ts index a0dae825856..bbc530fa7fd 100644 --- a/spacetime-crypto-ts/src/timing.ts +++ b/spacetime-crypto-ts/src/timing.ts @@ -20,33 +20,7 @@ export function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean { return diff === 0; } -/** Decode `01ab23cd` into Uint8Array. Throws on odd length or non-hex. */ -export function hexToBytes(hex: string): Uint8Array { - if (hex.length % 2 !== 0) throw new Error('hex: odd length'); - const out = new Uint8Array(hex.length / 2); - for (let i = 0; i < out.length; i++) { - const hi = hexNibble(hex.charCodeAt(i * 2)); - const lo = hexNibble(hex.charCodeAt(i * 2 + 1)); - out[i] = (hi << 4) | lo; - } - return out; -} - -function hexNibble(code: number): number { - if (code >= 0x30 && code <= 0x39) return code - 0x30; - if (code >= 0x61 && code <= 0x66) return code - 0x61 + 10; - if (code >= 0x41 && code <= 0x46) return code - 0x41 + 10; - throw new Error(`hex: non-hex char ${String.fromCharCode(code)}`); -} - -/** Encode bytes as lowercase hex. */ -export function bytesToHex(bytes: Uint8Array): string { - let s = ''; - for (let i = 0; i < bytes.length; i++) { - s += bytes[i].toString(16).padStart(2, '0'); - } - return s; -} +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 { From 5418e2f229c57f503d4306ae9e5fb6df29533f7d Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Thu, 17 Sep 2026 09:02:54 -0400 Subject: [PATCH 03/32] Address core submodule review and retry failure handling --- spacetime-cron-ts/LICENSE.txt | 960 ++++-------------- spacetime-cron-ts/README.md | 8 +- spacetime-cron-ts/example/README.md | 2 +- spacetime-cron-ts/package.json | 2 +- spacetime-crypto-ts/LICENSE.txt | 960 ++++-------------- spacetime-crypto-ts/README.md | 2 +- spacetime-crypto-ts/package.json | 2 +- spacetime-crypto-ts/scripts/test-vectors.ts | 2 +- spacetime-rate-limit-ts/LICENSE.txt | 960 ++++-------------- spacetime-rate-limit-ts/README.md | 4 +- spacetime-rate-limit-ts/example/README.md | 2 +- .../example/spacetimedb/src/index.ts | 12 +- spacetime-rate-limit-ts/package.json | 2 +- .../spacetimedb/src/index.ts | 2 +- spacetime-rate-limit-ts/src/submodule.ts | 2 +- .../src/submodule/operations.ts | 2 +- spacetime-retry-ts/LICENSE.txt | 960 ++++-------------- spacetime-retry-ts/README.md | 33 +- spacetime-retry-ts/package.json | 2 +- spacetime-retry-ts/scripts/test.ts | 88 +- spacetime-retry-ts/spacetimedb/src/index.ts | 13 +- spacetime-retry-ts/src/handler.ts | 6 +- spacetime-retry-ts/src/submodule.ts | 41 +- 23 files changed, 972 insertions(+), 3095 deletions(-) diff --git a/spacetime-cron-ts/LICENSE.txt b/spacetime-cron-ts/LICENSE.txt index ea0cb1c5e9e..4e61a2122e7 100644 --- a/spacetime-cron-ts/LICENSE.txt +++ b/spacetime-cron-ts/LICENSE.txt @@ -1,759 +1,201 @@ -SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT - -Business Source License 1.1 - -Parameters - -Licensor: Clockwork Laboratories, Inc. -Licensed Work: SpacetimeDB 2.8.3 - The Licensed Work is - (c) 2023 Clockwork Laboratories, Inc. - -Additional Use Grant: You may make use of the Licensed Work provided your - application or service uses the Licensed Work with no - more than one SpacetimeDB instance in production and - provided that you do not use the Licensed Work for a - Database Service. - - A “Database Service” is a commercial offering that - allows third parties (other than your employees and - contractors) to access the functionality of the - Licensed Work by creating tables whose schemas are - controlled by such third parties. - -Change Date: 2031-08-18 - -Change License: GNU Affero General Public License v3.0 with a linking - exception - -For information about alternative licensing arrangements for the Software, -please visit: https://spacetimedb.com - -Notice - -The Business Source License (this document, or the “License”) is not an Open -Source license. However, the Licensed Work will eventually be made available -under an Open Source License, as stated in this License. - -License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. -“Business Source License” is a trademark of MariaDB Corporation Ab. - ------------------------------------------------------------------------------ - -Base License and Subdirectory Specific Licenses - -1. Repository-Wide License -Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. - -2. Subdirectory-Specific Licenses -Certain subdirectories within this repository are licensed under different terms. - -If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. - -In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. - -3. Contributor Acknowledgement -By contributing to this repository, you agree that: - -Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. - -If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. - -4. Reading the Applicable License -Before using, modifying, or distributing code from this repository, you must read: - -This base LICENSE.txt file for the overall repository license. - -Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. - ------------------------------------------------------------------------------ - -Business Source License 1.1 - -Terms - -The Licensor hereby grants you the right to copy, modify, create derivative -works, redistribute, and make non-production use of the Licensed Work. The -Licensor may make an Additional Use Grant, above, permitting limited -production use. - -Effective on the Change Date, or the fourth anniversary of the first publicly -available distribution of a specific version of the Licensed Work under this -License, whichever comes first, the Licensor hereby grants you rights under -the terms of the Change License, and the rights granted in the paragraph -above terminate. - -If your use of the Licensed Work does not comply with the requirements -currently in effect as described in this License, you must purchase a -commercial license from the Licensor, its affiliated entities, or authorized -resellers, or you must refrain from using the Licensed Work. - -All copies of the original and modified Licensed Work, and derivative works -of the Licensed Work, are subject to this License. This License applies -separately for each version of the Licensed Work and the Change Date may vary -for each version of the Licensed Work released by Licensor. - -You must conspicuously display this License on each original or modified copy -of the Licensed Work. If you receive the Licensed Work in original or -modified form from a third party, the terms and conditions set forth in this -License apply to your use of that work. - -Any use of the Licensed Work in violation of this License will automatically -terminate your rights under this License for the current and all other -versions of the Licensed Work. - -This License does not grant you any right in any trademark or logo of -Licensor or its affiliates (provided that you may use a trademark or logo of -Licensor as expressly required by this License). - -TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON -AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, -EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND -TITLE. - -MariaDB hereby grants you permission to use this License’s text to license -your works, and to refer to it using the trademark “Business Source License”, -as long as you comply with the Covenants of Licensor below. - -Covenants of Licensor - -In consideration of the right to use this License’s text and the “Business -Source License” name and trademark, Licensor covenants to MariaDB, and to all -other recipients of the licensed work to be provided by Licensor: - -1. To specify as the Change License the GPL Version 2.0 or any later version, - or a license that is compatible with GPL Version 2.0 or a later version, - where “compatible” means that software provided under the Change License can - be included in a program with software provided under GPL Version 2.0 or a - later version. Licensor may specify additional Change Licenses without - limitation. - -2. To either: (a) specify an additional grant of rights to use that does not - impose any additional restriction on the right granted in this License, as - the Additional Use Grant; or (b) insert the text “None”. - -3. To specify a Change Date. - -4. Not to modify this License in any other way. - ------------------------------------------------------------------------------ - -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify it under -the terms of the GNU Affero General Public License, version 3, as published -by the Free Software Foundation. - -This program is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -details. - -You should have received a copy of the GNU Affero General Public License -along with this program; if not, see . - -Additional permission under GNU GPL version 3 section 7 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission to convey the resulting work. - -Additional permission under GNU AGPL version 3 section 13 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission that, notwithstanding any other provision of this -License, you need not prominently offer all users interacting with your -modified version remotely through a computer network an opportunity to -receive the Corresponding Source of your version from a network server at no -charge, if your version supports such interaction. This permission does not -waive or modify any other obligations or terms of the AGPL v3.0, except for -the specific requirement set forth in section 13. - -A copy of the AGPL v3.0 license is reproduced below. - - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - -Copyright © 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -Preamble -The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - -The licenses for most software and other practical works are designed to take -away your freedom to share and change the works. By contrast, our General -Public Licenses are intended to guarantee your freedom to share and change -all versions of a program--to make sure it remains free software for all its -users. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom -to distribute copies of free software (and charge for them if you wish), that -you receive source code or can get it if you want it, that you can change the -software or use pieces of it in new free programs, and that you know you can -do these things. - -Developers that use our General Public Licenses protect your rights with two -steps: (1) assert copyright on the software, and (2) offer you this License -which gives you legal permission to copy, distribute and/or modify the -software. - -A secondary benefit of defending all users' freedom is that improvements made -in alternate versions of the program, if they receive widespread use, become -available for other developers to incorporate. Many developers of free -software are heartened and encouraged by the resulting cooperation. However, -in the case of software used on network servers, this result may fail to come -about. The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its source -code to the public. - -The GNU Affero General Public License is designed specifically to ensure -that, in such cases, the modified source code becomes available to the -community. It requires the operator of a network server to provide the source -code of the modified version running there to the users of that server. -Therefore, public use of a modified version, on a publicly accessible server, -gives the public access to the source code of the modified version. - -An older license, called the Affero General Public License and published by -Affero, was designed to accomplish similar goals. This is a different -license, not a version of the Affero GPL, but Affero has released a new -version of the Affero GPL which permits relicensing under this license. - -The precise terms and conditions for copying, distribution and modification -follow. - -TERMS AND CONDITIONS -0. Definitions. -"This License" refers to version 3 of the GNU Affero General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this License. -Each licensee is addressed as "you". "Licensees" and "recipients" may be -individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work in a -fashion requiring copyright permission, other than the making of an exact -copy. The resulting work is called a "modified version" of the earlier work -or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based on the -Program. - -To "propagate" a work means to do anything with it that, without permission, -would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a -private copy. Propagation includes copying, distribution (with or without -modification), making available to the public, and in some countries other -activities as well. - -To "convey" a work means any kind of propagation that enables other parties -to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" to the -extent that it includes a convenient and prominently visible feature that (1) -displays an appropriate copyright notice, and (2) tells the user that there -is no warranty for the work (except to the extent that warranties are -provided), that licensees may convey the work under this License, and how to -view a copy of this License. If the interface presents a list of user -commands or options, such as a menu, a prominent item in the list meets this -criterion. - -1. Source Code. -The "source code" for a work means the preferred form of the work for making -modifications to it. "Object code" means any non-source form of a work. - -A "Standard Interface" means an interface that either is an official standard -defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used -among developers working in that language. - -The "System Libraries" of an executable work include anything, other than the -work as a whole, that (a) is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and (b) serves only -to enable use of the work with that Major Component, or to implement a -Standard Interface for which an implementation is available to the public in -source code form. A "Major Component", in this context, means a major -essential component (kernel, window system, and so on) of the specific -operating system (if any) on which the executable work runs, or a compiler -used to produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the -object code and to modify the work, including scripts to control those -activities. However, it does not include the work's System Libraries, or -general-purpose tools or generally available free programs which are used -unmodified in performing those activities but which are not part of the work. -For example, Corresponding Source includes interface definition files -associated with source files for the work, and the source code for shared -libraries and dynamically linked subprograms that the work is specifically -designed to require, such as by intimate data communication or control flow -between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -2. Basic Permissions. -All rights granted under this License are granted for the term of copyright -on the Program, and are irrevocable provided the stated conditions are met. -This License explicitly affirms your unlimited permission to run the -unmodified Program. The output from running a covered work is covered by this -License only if the output, given its content, constitutes a covered work. -This License acknowledges your rights of fair use or other equivalent, as -provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey -covered works to others for the sole purpose of having them make -modifications exclusively for you, or provide you with facilities for running -those works, provided that you comply with the terms of this License in -conveying all material for which you do not control copyright. Those thus -making or running the covered works for you must do so exclusively on your -behalf, under your direction and control, on terms that prohibit them from -making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes it -unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. -No covered work shall be deemed part of an effective technological measure -under any applicable law fulfilling obligations under article 11 of the WIPO -copyright treaty adopted on 20 December 1996, or similar laws prohibiting or -restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention is -effected by exercising rights under this License with respect to the covered -work, and you disclaim any intention to limit operation or modification of -the work as a means of enforcing, against the work's users, your or third -parties' legal rights to forbid circumvention of technological measures. - -4. Conveying Verbatim Copies. -You may convey verbatim copies of the Program's source code as you receive -it, in any medium, provided that you conspicuously and appropriately publish -on each copy an appropriate copyright notice; keep intact all notices stating -that this License and any non-permissive terms added in accord with section 7 -apply to the code; keep intact all notices of the absence of any warranty; -and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you -may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. -You may convey a work based on the Program, or the modifications to produce -it from the Program, in the form of source code under the terms of section 4, -provided that you also meet all of these conditions: - -a) The work must carry prominent notices stating that you modified it, and -giving a relevant date. -b) The work must carry prominent notices stating that it is released under -this License and any conditions added under section 7. This requirement -modifies the requirement in section 4 to "keep intact all notices". -c) You must license the entire work, as a whole, under this License to anyone -who comes into possession of a copy. This License will therefore apply, along -with any applicable section 7 additional terms, to the whole of the work, and -all its parts, regardless of how they are packaged. This License gives no -permission to license the work in any other way, but it does not invalidate -such permission if you have separately received it. -d) If the work has interactive user interfaces, each must display Appropriate -Legal Notices; however, if the Program has interactive interfaces that do not -display Appropriate Legal Notices, your work need not make them do so. -A compilation of a covered work with other separate and independent works, -which are not by their nature extensions of the covered work, and which are -not combined with it such as to form a larger program, in or on a volume of a -storage or distribution medium, is called an "aggregate" if the compilation -and its resulting copyright are not used to limit the access or legal rights -of the compilation's users beyond what the individual works permit. Inclusion -of a covered work in an aggregate does not cause this License to apply to the -other parts of the aggregate. - -6. Conveying Non-Source Forms. -You may convey a covered work in object code form under the terms of sections -4 and 5, provided that you also convey the machine-readable Corresponding -Source under the terms of this License, in one of these ways: - -a) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed -on a durable physical medium customarily used for software interchange. -b) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at -least three years and valid for as long as you offer spare parts or customer -support for that product model, to give anyone who possesses the object code -either (1) a copy of the Corresponding Source for all the software in the -product that is covered by this License, on a durable physical medium -customarily used for software interchange, for a price no more than your -reasonable cost of physically performing this conveying of source, or (2) -access to copy the Corresponding Source from a network server at no charge. -c) Convey individual copies of the object code with a copy of the written -offer to provide the Corresponding Source. This alternative is allowed only -occasionally and noncommercially, and only if you received the object code -with such an offer, in accord with subsection 6b. -d) Convey the object code by offering access from a designated place (gratis -or for a charge), and offer equivalent access to the Corresponding Source in -the same way through the same place at no further charge. You need not -require recipients to copy the Corresponding Source along with the object -code. If the place to copy the object code is a network server, the -Corresponding Source may be on a different server (operated by you or a third -party) that supports equivalent copying facilities, provided you maintain -clear directions next to the object code saying where to find the -Corresponding Source. Regardless of what server hosts the Corresponding -Source, you remain obligated to ensure that it is available for as long as -needed to satisfy these requirements. -e) Convey the object code using peer-to-peer transmission, provided you -inform other peers where the object code and Corresponding Source of the work -are being offered to the general public at no charge under subsection 6d. -A separable portion of the object code, whose source code is excluded from -the Corresponding Source as a System Library, need not be included in -conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any tangible -personal property which is normally used for personal, family, or household -purposes, or (2) anything designed or sold for incorporation into a dwelling. -In determining whether a product is a consumer product, doubtful cases shall -be resolved in favor of coverage. For a particular product received by a -particular user, "normally used" refers to a typical or common use of that -class of product, regardless of the status of the particular user or of the -way in which the particular user actually uses, or expects or is expected to -use, the product. A product is a consumer product regardless of whether the -product has substantial commercial, industrial or non-consumer uses, unless -such uses represent the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, procedures, -authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified -version of its Corresponding Source. The information must suffice to ensure -that the continued functioning of the modified object code is in no case -prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as part of -a transaction in which the right of possession and use of the User Product is -transferred to the recipient in perpetuity or for a fixed term (regardless of -how the transaction is characterized), the Corresponding Source conveyed -under this section must be accompanied by the Installation Information. But -this requirement does not apply if neither you nor any third party retains -the ability to install modified object code on the User Product (for example, -the work has been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates for -a work that has been modified or installed by the recipient, or for the User -Product in which it has been modified or installed. Access to a network may -be denied when the modification itself materially and adversely affects the -operation of the network or violates the rules and protocols for -communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in -accord with this section must be in a format that is publicly documented (and -with an implementation available to the public in source code form), and must -require no special password or key for unpacking, reading or copying. - -7. Additional Terms. -"Additional permissions" are terms that supplement the terms of this License -by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as -though they were included in this License, to the extent that they are valid -under applicable law. If additional permissions apply only to part of the -Program, that part may be used separately under those permissions, but the -entire Program remains governed by this License without regard to the -additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when -you modify the work.) You may place additional permissions on material, added -by you to a covered work, for which you have or can give appropriate -copyright permission. - -Notwithstanding any other provision of this License, for material you add to -a covered work, you may (if authorized by the copyright holders of that -material) supplement the terms of this License with terms: - -a) Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -b) Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed -by works containing it; or -c) Prohibiting misrepresentation of the origin of that material, or requiring -that modified versions of such material be marked in reasonable ways as -different from the original version; or -d) Limiting the use for publicity purposes of names of licensors or authors -of the material; or -e) Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -f) Requiring indemnification of licensors and authors of that material by -anyone who conveys the material (or modified versions of it) with contractual -assumptions of liability to the recipient, for any liability that these -contractual assumptions directly impose on those licensors and authors. -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is governed -by this License along with a term that is a further restriction, you may -remove that term. If a license document contains a further restriction but -permits relicensing or conveying under this License, you may add to a covered -work material governed by the terms of that license document, provided that -the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must -place, in the relevant source files, a statement of the additional terms that -apply to those files, or a notice indicating where to find the applicable -terms. - -Additional terms, permissive or non-permissive, may be stated in the form of -a separately written license, or stated as exceptions; the above requirements -apply either way. - -8. Termination. -You may not propagate or modify a covered work except as expressly provided -under this License. Any attempt otherwise to propagate or modify it is void, -and will automatically terminate your rights under this License (including -any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated (a) provisionally, unless and until -the copyright holder explicitly and finally terminates your license, and (b) -permanently, if the copyright holder fails to notify you of the violation by -some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated -permanently if the copyright holder notifies you of the violation by some -reasonable means, this is the first time you have received notice of -violation of this License (for any work) from that copyright holder, and you -cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses -of parties who have received copies or rights from you under this License. If -your rights have been terminated and not permanently reinstated, you do not -qualify to receive new licenses for the same material under section 10. - -9. Acceptance Not Required for Having Copies. -You are not required to accept this License in order to receive or run a copy -of the Program. Ancillary propagation of a covered work occurring solely as a -consequence of using peer-to-peer transmission to receive a copy likewise -does not require acceptance. However, nothing other than this License grants -you permission to propagate or modify any covered work. These actions -infringe copyright if you do not accept this License. Therefore, by modifying -or propagating a covered work, you indicate your acceptance of this License -to do so. - -10. Automatic Licensing of Downstream Recipients. -Each time you convey a covered work, the recipient automatically receives a -license from the original licensors, to run, modify and propagate that work, -subject to this License. You are not responsible for enforcing compliance by -third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered work -results from an entity transaction, each party to that transaction who -receives a copy of the work also receives whatever licenses to the work the -party's predecessor in interest had or could give under the previous -paragraph, plus a right to possession of the Corresponding Source of the work -from the predecessor in interest, if the predecessor has it or can get it -with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights -granted or affirmed under this License. For example, you may not impose a -license fee, royalty, or other charge for exercise of rights granted under -this License, and you may not initiate litigation (including a cross-claim or -counterclaim in a lawsuit) alleging that any patent claim is infringed by -making, using, selling, offering for sale, or importing the Program or any -portion of it. - -11. Patents. -A "contributor" is a copyright holder who authorizes use under this License -of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter -acquired, that would be infringed by some manner, permitted by this License, -of making, using, or selling its contributor version, but do not include -claims that would be infringed only as a consequence of further modification -of the contributor version. For purposes of this definition, "control" -includes the right to grant patent sublicenses in a manner consistent with -the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent -license under the contributor's essential patent claims, to make, use, sell, -offer for sale, import and otherwise run, modify and propagate the contents -of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent (such -as an express permission to practice a patent or covenant not to sue for -patent infringement). To "grant" such a patent license to a party means to -make such an agreement or commitment not to enforce a patent against the -party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of -charge and under the terms of this License, through a publicly available -network server or other readily accessible means, then you must either (1) -cause the Corresponding Source to be so available, or (2) arrange to deprive -yourself of the benefit of the patent license for this particular work, or -(3) arrange, in a manner consistent with the requirements of this License, to -extend the patent license to downstream recipients. "Knowingly relying" means -you have actual knowledge that, but for the patent license, your conveying -the covered work in a country, or your recipient's use of the covered work in -a country, would infringe one or more identifiable patents in that country -that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, -you convey, or propagate by procuring conveyance of, a covered work, and -grant a patent license to some of the parties receiving the covered work -authorizing them to use, propagate, modify or convey a specific copy of the -covered work, then the patent license you grant is automatically extended to -all recipients of the covered work and works based on it. - -A patent license is "discriminatory" if it does not include within the scope -of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under -this License. You may not convey a covered work if you are a party to an -arrangement with a third party that is in the business of distributing -software, under which you make payment to the third party based on the extent -of your activity of conveying the work, and under which the third party -grants, to any of the parties who would receive the covered work from you, a -discriminatory patent license (a) in connection with copies of the covered -work conveyed by you (or copies made from those copies), or (b) primarily for -and in connection with specific products or compilations that contain the -covered work, unless you entered into that arrangement, or that patent -license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any -implied license or other defenses to infringement that may otherwise be -available to you under applicable patent law. - -12. No Surrender of Others' Freedom. -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not excuse -you from the conditions of this License. If you cannot convey a covered work -so as to satisfy simultaneously your obligations under this License and any -other pertinent obligations, then as a consequence you may not convey it at -all. For example, if you agree to terms that obligate you to collect a -royalty for further conveying from those to whom you convey the Program, the -only way you could satisfy both those terms and this License would be to -refrain entirely from conveying the Program. - -13. Remote Network Interaction; Use with the GNU General Public License. -Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users interacting -with it remotely through a computer network (if your version supports such -interaction) an opportunity to receive the Corresponding Source of your -version by providing access to the Corresponding Source from a network server -at no charge, through some standard or customary means of facilitating -copying of software. This Corresponding Source shall include the -Corresponding Source for any work covered by version 3 of the GNU General -Public License that is incorporated pursuant to the following paragraph. - -Notwithstanding any other provision of this License, you have permission to -link or combine any covered work with a work licensed under version 3 of the -GNU General Public License into a single combined work, and to convey the -resulting work. The terms of this License will continue to apply to the part -which is the covered work, but the work with which it is combined will remain -governed by version 3 of the GNU General Public License. - -14. Revised Versions of this License. -The Free Software Foundation may publish revised and/or new versions of the -GNU Affero General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU Affero General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or of any -later version published by the Free Software Foundation. If the Program does -not specify a version number of the GNU Affero General Public License, you -may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the -GNU Affero General Public License can be used, that proxy's public statement -of acceptance of a version permanently authorizes you to choose that version -for the Program. - -Later license versions may give you additional or different permissions. -However, no additional obligations are imposed on any author or copyright -holder as a result of your choosing to follow a later version. - -15. Disclaimer of Warranty. -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE -LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, -EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. -SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY -SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL -ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE -PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE -OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR -DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR -A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH -HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. -If the disclaimer of warranty and limitation of liability provided above -cannot be given local legal effect according to their terms, reviewing courts -shall apply local law that most closely approximates an absolute waiver of -all civil liability in connection with the Program, unless a warranty or -assumption of liability accompanies a copy of the Program in return for a -fee. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Programs -If you develop a new program, and you want it to be of the greatest possible -use to the public, the best way to achieve this is to make it free software -which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach -them to the start of each source file to most effectively state the exclusion -of warranty; and each file should have at least the "copyright" line and a -pointer to where the full notice is found. - -SpacetimeDB: A database which replaces your server. -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -Also add information on how to contact you by electronic and paper mail. - -If your software can interact with users remotely through a computer network, -you should also make sure that it provides a way for users to get its source. -For example, if your program is a web application, its interface could -display a "Source" link that leads users to an archive of the code. There are -many ways you could offer source, and different solutions will be better for -different programs; see section 13 for the specific requirements. - -You should also get your employer (if you work as a programmer) or school, if -any, to sign a "copyright disclaimer" for the program, if necessary. For more -information on this, and how to apply and follow the GNU AGPL, see -. + 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 index 21f12bff947..67b1d72a264 100644 --- a/spacetime-cron-ts/README.md +++ b/spacetime-cron-ts/README.md @@ -10,8 +10,8 @@ transactions are available. ## Requirements -- SpacetimeDB CLI 2.8.3 -- `spacetimedb` npm package 2.8.3 +- SpacetimeDB CLI 2.8.3 or later +- 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 @@ -19,7 +19,7 @@ transactions are available. ## Install ```bash -npm install @spacetimedb/cron spacetimedb@^2.8.3 +npm install @spacetimedb/cron spacetimedb ``` `spacetimedb` is a peer dependency. Use the same SDK version for the application module and this package. @@ -386,4 +386,4 @@ See the [browser example](./example/) for a complete integration. ## License -BUSL-1.1. See [`LICENSE.txt`](./LICENSE.txt). +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-cron-ts/example/README.md b/spacetime-cron-ts/example/README.md index d6080ed7558..705a53b9298 100644 --- a/spacetime-cron-ts/example/README.md +++ b/spacetime-cron-ts/example/README.md @@ -72,7 +72,7 @@ This workspace tests the submodule source in this repository. Consumer applications install the published release: ```bash -npm install @spacetimedb/cron spacetimedb@^2.8.3 +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). diff --git a/spacetime-cron-ts/package.json b/spacetime-cron-ts/package.json index d7469942d48..808da1f0c00 100644 --- a/spacetime-cron-ts/package.json +++ b/spacetime-cron-ts/package.json @@ -2,7 +2,7 @@ "name": "@spacetimedb/cron", "description": "Calendar and interval scheduling for SpacetimeDB TypeScript modules.", "version": "0.3.0", - "license": "BUSL-1.1", + "license": "Apache-2.0", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/spacetime-crypto-ts/LICENSE.txt b/spacetime-crypto-ts/LICENSE.txt index ea0cb1c5e9e..4e61a2122e7 100644 --- a/spacetime-crypto-ts/LICENSE.txt +++ b/spacetime-crypto-ts/LICENSE.txt @@ -1,759 +1,201 @@ -SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT - -Business Source License 1.1 - -Parameters - -Licensor: Clockwork Laboratories, Inc. -Licensed Work: SpacetimeDB 2.8.3 - The Licensed Work is - (c) 2023 Clockwork Laboratories, Inc. - -Additional Use Grant: You may make use of the Licensed Work provided your - application or service uses the Licensed Work with no - more than one SpacetimeDB instance in production and - provided that you do not use the Licensed Work for a - Database Service. - - A “Database Service” is a commercial offering that - allows third parties (other than your employees and - contractors) to access the functionality of the - Licensed Work by creating tables whose schemas are - controlled by such third parties. - -Change Date: 2031-08-18 - -Change License: GNU Affero General Public License v3.0 with a linking - exception - -For information about alternative licensing arrangements for the Software, -please visit: https://spacetimedb.com - -Notice - -The Business Source License (this document, or the “License”) is not an Open -Source license. However, the Licensed Work will eventually be made available -under an Open Source License, as stated in this License. - -License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. -“Business Source License” is a trademark of MariaDB Corporation Ab. - ------------------------------------------------------------------------------ - -Base License and Subdirectory Specific Licenses - -1. Repository-Wide License -Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. - -2. Subdirectory-Specific Licenses -Certain subdirectories within this repository are licensed under different terms. - -If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. - -In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. - -3. Contributor Acknowledgement -By contributing to this repository, you agree that: - -Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. - -If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. - -4. Reading the Applicable License -Before using, modifying, or distributing code from this repository, you must read: - -This base LICENSE.txt file for the overall repository license. - -Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. - ------------------------------------------------------------------------------ - -Business Source License 1.1 - -Terms - -The Licensor hereby grants you the right to copy, modify, create derivative -works, redistribute, and make non-production use of the Licensed Work. The -Licensor may make an Additional Use Grant, above, permitting limited -production use. - -Effective on the Change Date, or the fourth anniversary of the first publicly -available distribution of a specific version of the Licensed Work under this -License, whichever comes first, the Licensor hereby grants you rights under -the terms of the Change License, and the rights granted in the paragraph -above terminate. - -If your use of the Licensed Work does not comply with the requirements -currently in effect as described in this License, you must purchase a -commercial license from the Licensor, its affiliated entities, or authorized -resellers, or you must refrain from using the Licensed Work. - -All copies of the original and modified Licensed Work, and derivative works -of the Licensed Work, are subject to this License. This License applies -separately for each version of the Licensed Work and the Change Date may vary -for each version of the Licensed Work released by Licensor. - -You must conspicuously display this License on each original or modified copy -of the Licensed Work. If you receive the Licensed Work in original or -modified form from a third party, the terms and conditions set forth in this -License apply to your use of that work. - -Any use of the Licensed Work in violation of this License will automatically -terminate your rights under this License for the current and all other -versions of the Licensed Work. - -This License does not grant you any right in any trademark or logo of -Licensor or its affiliates (provided that you may use a trademark or logo of -Licensor as expressly required by this License). - -TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON -AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, -EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND -TITLE. - -MariaDB hereby grants you permission to use this License’s text to license -your works, and to refer to it using the trademark “Business Source License”, -as long as you comply with the Covenants of Licensor below. - -Covenants of Licensor - -In consideration of the right to use this License’s text and the “Business -Source License” name and trademark, Licensor covenants to MariaDB, and to all -other recipients of the licensed work to be provided by Licensor: - -1. To specify as the Change License the GPL Version 2.0 or any later version, - or a license that is compatible with GPL Version 2.0 or a later version, - where “compatible” means that software provided under the Change License can - be included in a program with software provided under GPL Version 2.0 or a - later version. Licensor may specify additional Change Licenses without - limitation. - -2. To either: (a) specify an additional grant of rights to use that does not - impose any additional restriction on the right granted in this License, as - the Additional Use Grant; or (b) insert the text “None”. - -3. To specify a Change Date. - -4. Not to modify this License in any other way. - ------------------------------------------------------------------------------ - -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify it under -the terms of the GNU Affero General Public License, version 3, as published -by the Free Software Foundation. - -This program is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -details. - -You should have received a copy of the GNU Affero General Public License -along with this program; if not, see . - -Additional permission under GNU GPL version 3 section 7 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission to convey the resulting work. - -Additional permission under GNU AGPL version 3 section 13 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission that, notwithstanding any other provision of this -License, you need not prominently offer all users interacting with your -modified version remotely through a computer network an opportunity to -receive the Corresponding Source of your version from a network server at no -charge, if your version supports such interaction. This permission does not -waive or modify any other obligations or terms of the AGPL v3.0, except for -the specific requirement set forth in section 13. - -A copy of the AGPL v3.0 license is reproduced below. - - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - -Copyright © 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -Preamble -The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - -The licenses for most software and other practical works are designed to take -away your freedom to share and change the works. By contrast, our General -Public Licenses are intended to guarantee your freedom to share and change -all versions of a program--to make sure it remains free software for all its -users. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom -to distribute copies of free software (and charge for them if you wish), that -you receive source code or can get it if you want it, that you can change the -software or use pieces of it in new free programs, and that you know you can -do these things. - -Developers that use our General Public Licenses protect your rights with two -steps: (1) assert copyright on the software, and (2) offer you this License -which gives you legal permission to copy, distribute and/or modify the -software. - -A secondary benefit of defending all users' freedom is that improvements made -in alternate versions of the program, if they receive widespread use, become -available for other developers to incorporate. Many developers of free -software are heartened and encouraged by the resulting cooperation. However, -in the case of software used on network servers, this result may fail to come -about. The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its source -code to the public. - -The GNU Affero General Public License is designed specifically to ensure -that, in such cases, the modified source code becomes available to the -community. It requires the operator of a network server to provide the source -code of the modified version running there to the users of that server. -Therefore, public use of a modified version, on a publicly accessible server, -gives the public access to the source code of the modified version. - -An older license, called the Affero General Public License and published by -Affero, was designed to accomplish similar goals. This is a different -license, not a version of the Affero GPL, but Affero has released a new -version of the Affero GPL which permits relicensing under this license. - -The precise terms and conditions for copying, distribution and modification -follow. - -TERMS AND CONDITIONS -0. Definitions. -"This License" refers to version 3 of the GNU Affero General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this License. -Each licensee is addressed as "you". "Licensees" and "recipients" may be -individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work in a -fashion requiring copyright permission, other than the making of an exact -copy. The resulting work is called a "modified version" of the earlier work -or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based on the -Program. - -To "propagate" a work means to do anything with it that, without permission, -would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a -private copy. Propagation includes copying, distribution (with or without -modification), making available to the public, and in some countries other -activities as well. - -To "convey" a work means any kind of propagation that enables other parties -to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" to the -extent that it includes a convenient and prominently visible feature that (1) -displays an appropriate copyright notice, and (2) tells the user that there -is no warranty for the work (except to the extent that warranties are -provided), that licensees may convey the work under this License, and how to -view a copy of this License. If the interface presents a list of user -commands or options, such as a menu, a prominent item in the list meets this -criterion. - -1. Source Code. -The "source code" for a work means the preferred form of the work for making -modifications to it. "Object code" means any non-source form of a work. - -A "Standard Interface" means an interface that either is an official standard -defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used -among developers working in that language. - -The "System Libraries" of an executable work include anything, other than the -work as a whole, that (a) is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and (b) serves only -to enable use of the work with that Major Component, or to implement a -Standard Interface for which an implementation is available to the public in -source code form. A "Major Component", in this context, means a major -essential component (kernel, window system, and so on) of the specific -operating system (if any) on which the executable work runs, or a compiler -used to produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the -object code and to modify the work, including scripts to control those -activities. However, it does not include the work's System Libraries, or -general-purpose tools or generally available free programs which are used -unmodified in performing those activities but which are not part of the work. -For example, Corresponding Source includes interface definition files -associated with source files for the work, and the source code for shared -libraries and dynamically linked subprograms that the work is specifically -designed to require, such as by intimate data communication or control flow -between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -2. Basic Permissions. -All rights granted under this License are granted for the term of copyright -on the Program, and are irrevocable provided the stated conditions are met. -This License explicitly affirms your unlimited permission to run the -unmodified Program. The output from running a covered work is covered by this -License only if the output, given its content, constitutes a covered work. -This License acknowledges your rights of fair use or other equivalent, as -provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey -covered works to others for the sole purpose of having them make -modifications exclusively for you, or provide you with facilities for running -those works, provided that you comply with the terms of this License in -conveying all material for which you do not control copyright. Those thus -making or running the covered works for you must do so exclusively on your -behalf, under your direction and control, on terms that prohibit them from -making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes it -unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. -No covered work shall be deemed part of an effective technological measure -under any applicable law fulfilling obligations under article 11 of the WIPO -copyright treaty adopted on 20 December 1996, or similar laws prohibiting or -restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention is -effected by exercising rights under this License with respect to the covered -work, and you disclaim any intention to limit operation or modification of -the work as a means of enforcing, against the work's users, your or third -parties' legal rights to forbid circumvention of technological measures. - -4. Conveying Verbatim Copies. -You may convey verbatim copies of the Program's source code as you receive -it, in any medium, provided that you conspicuously and appropriately publish -on each copy an appropriate copyright notice; keep intact all notices stating -that this License and any non-permissive terms added in accord with section 7 -apply to the code; keep intact all notices of the absence of any warranty; -and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you -may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. -You may convey a work based on the Program, or the modifications to produce -it from the Program, in the form of source code under the terms of section 4, -provided that you also meet all of these conditions: - -a) The work must carry prominent notices stating that you modified it, and -giving a relevant date. -b) The work must carry prominent notices stating that it is released under -this License and any conditions added under section 7. This requirement -modifies the requirement in section 4 to "keep intact all notices". -c) You must license the entire work, as a whole, under this License to anyone -who comes into possession of a copy. This License will therefore apply, along -with any applicable section 7 additional terms, to the whole of the work, and -all its parts, regardless of how they are packaged. This License gives no -permission to license the work in any other way, but it does not invalidate -such permission if you have separately received it. -d) If the work has interactive user interfaces, each must display Appropriate -Legal Notices; however, if the Program has interactive interfaces that do not -display Appropriate Legal Notices, your work need not make them do so. -A compilation of a covered work with other separate and independent works, -which are not by their nature extensions of the covered work, and which are -not combined with it such as to form a larger program, in or on a volume of a -storage or distribution medium, is called an "aggregate" if the compilation -and its resulting copyright are not used to limit the access or legal rights -of the compilation's users beyond what the individual works permit. Inclusion -of a covered work in an aggregate does not cause this License to apply to the -other parts of the aggregate. - -6. Conveying Non-Source Forms. -You may convey a covered work in object code form under the terms of sections -4 and 5, provided that you also convey the machine-readable Corresponding -Source under the terms of this License, in one of these ways: - -a) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed -on a durable physical medium customarily used for software interchange. -b) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at -least three years and valid for as long as you offer spare parts or customer -support for that product model, to give anyone who possesses the object code -either (1) a copy of the Corresponding Source for all the software in the -product that is covered by this License, on a durable physical medium -customarily used for software interchange, for a price no more than your -reasonable cost of physically performing this conveying of source, or (2) -access to copy the Corresponding Source from a network server at no charge. -c) Convey individual copies of the object code with a copy of the written -offer to provide the Corresponding Source. This alternative is allowed only -occasionally and noncommercially, and only if you received the object code -with such an offer, in accord with subsection 6b. -d) Convey the object code by offering access from a designated place (gratis -or for a charge), and offer equivalent access to the Corresponding Source in -the same way through the same place at no further charge. You need not -require recipients to copy the Corresponding Source along with the object -code. If the place to copy the object code is a network server, the -Corresponding Source may be on a different server (operated by you or a third -party) that supports equivalent copying facilities, provided you maintain -clear directions next to the object code saying where to find the -Corresponding Source. Regardless of what server hosts the Corresponding -Source, you remain obligated to ensure that it is available for as long as -needed to satisfy these requirements. -e) Convey the object code using peer-to-peer transmission, provided you -inform other peers where the object code and Corresponding Source of the work -are being offered to the general public at no charge under subsection 6d. -A separable portion of the object code, whose source code is excluded from -the Corresponding Source as a System Library, need not be included in -conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any tangible -personal property which is normally used for personal, family, or household -purposes, or (2) anything designed or sold for incorporation into a dwelling. -In determining whether a product is a consumer product, doubtful cases shall -be resolved in favor of coverage. For a particular product received by a -particular user, "normally used" refers to a typical or common use of that -class of product, regardless of the status of the particular user or of the -way in which the particular user actually uses, or expects or is expected to -use, the product. A product is a consumer product regardless of whether the -product has substantial commercial, industrial or non-consumer uses, unless -such uses represent the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, procedures, -authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified -version of its Corresponding Source. The information must suffice to ensure -that the continued functioning of the modified object code is in no case -prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as part of -a transaction in which the right of possession and use of the User Product is -transferred to the recipient in perpetuity or for a fixed term (regardless of -how the transaction is characterized), the Corresponding Source conveyed -under this section must be accompanied by the Installation Information. But -this requirement does not apply if neither you nor any third party retains -the ability to install modified object code on the User Product (for example, -the work has been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates for -a work that has been modified or installed by the recipient, or for the User -Product in which it has been modified or installed. Access to a network may -be denied when the modification itself materially and adversely affects the -operation of the network or violates the rules and protocols for -communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in -accord with this section must be in a format that is publicly documented (and -with an implementation available to the public in source code form), and must -require no special password or key for unpacking, reading or copying. - -7. Additional Terms. -"Additional permissions" are terms that supplement the terms of this License -by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as -though they were included in this License, to the extent that they are valid -under applicable law. If additional permissions apply only to part of the -Program, that part may be used separately under those permissions, but the -entire Program remains governed by this License without regard to the -additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when -you modify the work.) You may place additional permissions on material, added -by you to a covered work, for which you have or can give appropriate -copyright permission. - -Notwithstanding any other provision of this License, for material you add to -a covered work, you may (if authorized by the copyright holders of that -material) supplement the terms of this License with terms: - -a) Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -b) Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed -by works containing it; or -c) Prohibiting misrepresentation of the origin of that material, or requiring -that modified versions of such material be marked in reasonable ways as -different from the original version; or -d) Limiting the use for publicity purposes of names of licensors or authors -of the material; or -e) Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -f) Requiring indemnification of licensors and authors of that material by -anyone who conveys the material (or modified versions of it) with contractual -assumptions of liability to the recipient, for any liability that these -contractual assumptions directly impose on those licensors and authors. -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is governed -by this License along with a term that is a further restriction, you may -remove that term. If a license document contains a further restriction but -permits relicensing or conveying under this License, you may add to a covered -work material governed by the terms of that license document, provided that -the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must -place, in the relevant source files, a statement of the additional terms that -apply to those files, or a notice indicating where to find the applicable -terms. - -Additional terms, permissive or non-permissive, may be stated in the form of -a separately written license, or stated as exceptions; the above requirements -apply either way. - -8. Termination. -You may not propagate or modify a covered work except as expressly provided -under this License. Any attempt otherwise to propagate or modify it is void, -and will automatically terminate your rights under this License (including -any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated (a) provisionally, unless and until -the copyright holder explicitly and finally terminates your license, and (b) -permanently, if the copyright holder fails to notify you of the violation by -some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated -permanently if the copyright holder notifies you of the violation by some -reasonable means, this is the first time you have received notice of -violation of this License (for any work) from that copyright holder, and you -cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses -of parties who have received copies or rights from you under this License. If -your rights have been terminated and not permanently reinstated, you do not -qualify to receive new licenses for the same material under section 10. - -9. Acceptance Not Required for Having Copies. -You are not required to accept this License in order to receive or run a copy -of the Program. Ancillary propagation of a covered work occurring solely as a -consequence of using peer-to-peer transmission to receive a copy likewise -does not require acceptance. However, nothing other than this License grants -you permission to propagate or modify any covered work. These actions -infringe copyright if you do not accept this License. Therefore, by modifying -or propagating a covered work, you indicate your acceptance of this License -to do so. - -10. Automatic Licensing of Downstream Recipients. -Each time you convey a covered work, the recipient automatically receives a -license from the original licensors, to run, modify and propagate that work, -subject to this License. You are not responsible for enforcing compliance by -third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered work -results from an entity transaction, each party to that transaction who -receives a copy of the work also receives whatever licenses to the work the -party's predecessor in interest had or could give under the previous -paragraph, plus a right to possession of the Corresponding Source of the work -from the predecessor in interest, if the predecessor has it or can get it -with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights -granted or affirmed under this License. For example, you may not impose a -license fee, royalty, or other charge for exercise of rights granted under -this License, and you may not initiate litigation (including a cross-claim or -counterclaim in a lawsuit) alleging that any patent claim is infringed by -making, using, selling, offering for sale, or importing the Program or any -portion of it. - -11. Patents. -A "contributor" is a copyright holder who authorizes use under this License -of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter -acquired, that would be infringed by some manner, permitted by this License, -of making, using, or selling its contributor version, but do not include -claims that would be infringed only as a consequence of further modification -of the contributor version. For purposes of this definition, "control" -includes the right to grant patent sublicenses in a manner consistent with -the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent -license under the contributor's essential patent claims, to make, use, sell, -offer for sale, import and otherwise run, modify and propagate the contents -of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent (such -as an express permission to practice a patent or covenant not to sue for -patent infringement). To "grant" such a patent license to a party means to -make such an agreement or commitment not to enforce a patent against the -party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of -charge and under the terms of this License, through a publicly available -network server or other readily accessible means, then you must either (1) -cause the Corresponding Source to be so available, or (2) arrange to deprive -yourself of the benefit of the patent license for this particular work, or -(3) arrange, in a manner consistent with the requirements of this License, to -extend the patent license to downstream recipients. "Knowingly relying" means -you have actual knowledge that, but for the patent license, your conveying -the covered work in a country, or your recipient's use of the covered work in -a country, would infringe one or more identifiable patents in that country -that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, -you convey, or propagate by procuring conveyance of, a covered work, and -grant a patent license to some of the parties receiving the covered work -authorizing them to use, propagate, modify or convey a specific copy of the -covered work, then the patent license you grant is automatically extended to -all recipients of the covered work and works based on it. - -A patent license is "discriminatory" if it does not include within the scope -of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under -this License. You may not convey a covered work if you are a party to an -arrangement with a third party that is in the business of distributing -software, under which you make payment to the third party based on the extent -of your activity of conveying the work, and under which the third party -grants, to any of the parties who would receive the covered work from you, a -discriminatory patent license (a) in connection with copies of the covered -work conveyed by you (or copies made from those copies), or (b) primarily for -and in connection with specific products or compilations that contain the -covered work, unless you entered into that arrangement, or that patent -license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any -implied license or other defenses to infringement that may otherwise be -available to you under applicable patent law. - -12. No Surrender of Others' Freedom. -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not excuse -you from the conditions of this License. If you cannot convey a covered work -so as to satisfy simultaneously your obligations under this License and any -other pertinent obligations, then as a consequence you may not convey it at -all. For example, if you agree to terms that obligate you to collect a -royalty for further conveying from those to whom you convey the Program, the -only way you could satisfy both those terms and this License would be to -refrain entirely from conveying the Program. - -13. Remote Network Interaction; Use with the GNU General Public License. -Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users interacting -with it remotely through a computer network (if your version supports such -interaction) an opportunity to receive the Corresponding Source of your -version by providing access to the Corresponding Source from a network server -at no charge, through some standard or customary means of facilitating -copying of software. This Corresponding Source shall include the -Corresponding Source for any work covered by version 3 of the GNU General -Public License that is incorporated pursuant to the following paragraph. - -Notwithstanding any other provision of this License, you have permission to -link or combine any covered work with a work licensed under version 3 of the -GNU General Public License into a single combined work, and to convey the -resulting work. The terms of this License will continue to apply to the part -which is the covered work, but the work with which it is combined will remain -governed by version 3 of the GNU General Public License. - -14. Revised Versions of this License. -The Free Software Foundation may publish revised and/or new versions of the -GNU Affero General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU Affero General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or of any -later version published by the Free Software Foundation. If the Program does -not specify a version number of the GNU Affero General Public License, you -may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the -GNU Affero General Public License can be used, that proxy's public statement -of acceptance of a version permanently authorizes you to choose that version -for the Program. - -Later license versions may give you additional or different permissions. -However, no additional obligations are imposed on any author or copyright -holder as a result of your choosing to follow a later version. - -15. Disclaimer of Warranty. -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE -LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, -EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. -SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY -SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL -ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE -PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE -OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR -DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR -A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH -HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. -If the disclaimer of warranty and limitation of liability provided above -cannot be given local legal effect according to their terms, reviewing courts -shall apply local law that most closely approximates an absolute waiver of -all civil liability in connection with the Program, unless a warranty or -assumption of liability accompanies a copy of the Program in return for a -fee. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Programs -If you develop a new program, and you want it to be of the greatest possible -use to the public, the best way to achieve this is to make it free software -which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach -them to the start of each source file to most effectively state the exclusion -of warranty; and each file should have at least the "copyright" line and a -pointer to where the full notice is found. - -SpacetimeDB: A database which replaces your server. -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -Also add information on how to contact you by electronic and paper mail. - -If your software can interact with users remotely through a computer network, -you should also make sure that it provides a way for users to get its source. -For example, if your program is a web application, its interface could -display a "Source" link that leads users to an archive of the code. There are -many ways you could offer source, and different solutions will be better for -different programs; see section 13 for the specific requirements. - -You should also get your employer (if you work as a programmer) or school, if -any, to sign a "copyright disclaimer" for the program, if necessary. For more -information on this, and how to apply and follow the GNU AGPL, see -. + 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 index f6a7dc2d516..64b2192ef28 100644 --- a/spacetime-crypto-ts/README.md +++ b/spacetime-crypto-ts/README.md @@ -68,4 +68,4 @@ Tests use published vendor vectors and local fixtures; no network is required. ## License -BUSL-1.1. See [`LICENSE.txt`](./LICENSE.txt). +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-crypto-ts/package.json b/spacetime-crypto-ts/package.json index 04c4900a497..e6b20c42870 100644 --- a/spacetime-crypto-ts/package.json +++ b/spacetime-crypto-ts/package.json @@ -2,7 +2,7 @@ "name": "@spacetimedb/crypto", "description": "Deterministic hashing, encoding, and webhook-signature helpers for SpacetimeDB TypeScript modules.", "version": "0.1.0", - "license": "BUSL-1.1", + "license": "Apache-2.0", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/spacetime-crypto-ts/scripts/test-vectors.ts b/spacetime-crypto-ts/scripts/test-vectors.ts index cabc15d1ee3..4d38209cd96 100644 --- a/spacetime-crypto-ts/scripts/test-vectors.ts +++ b/spacetime-crypto-ts/scripts/test-vectors.ts @@ -1,4 +1,4 @@ -// Verify the pure-TS implementations against published test vectors. +// Verify the @noble/hashes wrappers and signature helpers against test vectors. // Run via: pnpm test // // Sources: diff --git a/spacetime-rate-limit-ts/LICENSE.txt b/spacetime-rate-limit-ts/LICENSE.txt index ea0cb1c5e9e..4e61a2122e7 100644 --- a/spacetime-rate-limit-ts/LICENSE.txt +++ b/spacetime-rate-limit-ts/LICENSE.txt @@ -1,759 +1,201 @@ -SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT - -Business Source License 1.1 - -Parameters - -Licensor: Clockwork Laboratories, Inc. -Licensed Work: SpacetimeDB 2.8.3 - The Licensed Work is - (c) 2023 Clockwork Laboratories, Inc. - -Additional Use Grant: You may make use of the Licensed Work provided your - application or service uses the Licensed Work with no - more than one SpacetimeDB instance in production and - provided that you do not use the Licensed Work for a - Database Service. - - A “Database Service” is a commercial offering that - allows third parties (other than your employees and - contractors) to access the functionality of the - Licensed Work by creating tables whose schemas are - controlled by such third parties. - -Change Date: 2031-08-18 - -Change License: GNU Affero General Public License v3.0 with a linking - exception - -For information about alternative licensing arrangements for the Software, -please visit: https://spacetimedb.com - -Notice - -The Business Source License (this document, or the “License”) is not an Open -Source license. However, the Licensed Work will eventually be made available -under an Open Source License, as stated in this License. - -License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. -“Business Source License” is a trademark of MariaDB Corporation Ab. - ------------------------------------------------------------------------------ - -Base License and Subdirectory Specific Licenses - -1. Repository-Wide License -Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. - -2. Subdirectory-Specific Licenses -Certain subdirectories within this repository are licensed under different terms. - -If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. - -In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. - -3. Contributor Acknowledgement -By contributing to this repository, you agree that: - -Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. - -If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. - -4. Reading the Applicable License -Before using, modifying, or distributing code from this repository, you must read: - -This base LICENSE.txt file for the overall repository license. - -Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. - ------------------------------------------------------------------------------ - -Business Source License 1.1 - -Terms - -The Licensor hereby grants you the right to copy, modify, create derivative -works, redistribute, and make non-production use of the Licensed Work. The -Licensor may make an Additional Use Grant, above, permitting limited -production use. - -Effective on the Change Date, or the fourth anniversary of the first publicly -available distribution of a specific version of the Licensed Work under this -License, whichever comes first, the Licensor hereby grants you rights under -the terms of the Change License, and the rights granted in the paragraph -above terminate. - -If your use of the Licensed Work does not comply with the requirements -currently in effect as described in this License, you must purchase a -commercial license from the Licensor, its affiliated entities, or authorized -resellers, or you must refrain from using the Licensed Work. - -All copies of the original and modified Licensed Work, and derivative works -of the Licensed Work, are subject to this License. This License applies -separately for each version of the Licensed Work and the Change Date may vary -for each version of the Licensed Work released by Licensor. - -You must conspicuously display this License on each original or modified copy -of the Licensed Work. If you receive the Licensed Work in original or -modified form from a third party, the terms and conditions set forth in this -License apply to your use of that work. - -Any use of the Licensed Work in violation of this License will automatically -terminate your rights under this License for the current and all other -versions of the Licensed Work. - -This License does not grant you any right in any trademark or logo of -Licensor or its affiliates (provided that you may use a trademark or logo of -Licensor as expressly required by this License). - -TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON -AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, -EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND -TITLE. - -MariaDB hereby grants you permission to use this License’s text to license -your works, and to refer to it using the trademark “Business Source License”, -as long as you comply with the Covenants of Licensor below. - -Covenants of Licensor - -In consideration of the right to use this License’s text and the “Business -Source License” name and trademark, Licensor covenants to MariaDB, and to all -other recipients of the licensed work to be provided by Licensor: - -1. To specify as the Change License the GPL Version 2.0 or any later version, - or a license that is compatible with GPL Version 2.0 or a later version, - where “compatible” means that software provided under the Change License can - be included in a program with software provided under GPL Version 2.0 or a - later version. Licensor may specify additional Change Licenses without - limitation. - -2. To either: (a) specify an additional grant of rights to use that does not - impose any additional restriction on the right granted in this License, as - the Additional Use Grant; or (b) insert the text “None”. - -3. To specify a Change Date. - -4. Not to modify this License in any other way. - ------------------------------------------------------------------------------ - -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify it under -the terms of the GNU Affero General Public License, version 3, as published -by the Free Software Foundation. - -This program is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -details. - -You should have received a copy of the GNU Affero General Public License -along with this program; if not, see . - -Additional permission under GNU GPL version 3 section 7 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission to convey the resulting work. - -Additional permission under GNU AGPL version 3 section 13 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission that, notwithstanding any other provision of this -License, you need not prominently offer all users interacting with your -modified version remotely through a computer network an opportunity to -receive the Corresponding Source of your version from a network server at no -charge, if your version supports such interaction. This permission does not -waive or modify any other obligations or terms of the AGPL v3.0, except for -the specific requirement set forth in section 13. - -A copy of the AGPL v3.0 license is reproduced below. - - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - -Copyright © 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -Preamble -The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - -The licenses for most software and other practical works are designed to take -away your freedom to share and change the works. By contrast, our General -Public Licenses are intended to guarantee your freedom to share and change -all versions of a program--to make sure it remains free software for all its -users. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom -to distribute copies of free software (and charge for them if you wish), that -you receive source code or can get it if you want it, that you can change the -software or use pieces of it in new free programs, and that you know you can -do these things. - -Developers that use our General Public Licenses protect your rights with two -steps: (1) assert copyright on the software, and (2) offer you this License -which gives you legal permission to copy, distribute and/or modify the -software. - -A secondary benefit of defending all users' freedom is that improvements made -in alternate versions of the program, if they receive widespread use, become -available for other developers to incorporate. Many developers of free -software are heartened and encouraged by the resulting cooperation. However, -in the case of software used on network servers, this result may fail to come -about. The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its source -code to the public. - -The GNU Affero General Public License is designed specifically to ensure -that, in such cases, the modified source code becomes available to the -community. It requires the operator of a network server to provide the source -code of the modified version running there to the users of that server. -Therefore, public use of a modified version, on a publicly accessible server, -gives the public access to the source code of the modified version. - -An older license, called the Affero General Public License and published by -Affero, was designed to accomplish similar goals. This is a different -license, not a version of the Affero GPL, but Affero has released a new -version of the Affero GPL which permits relicensing under this license. - -The precise terms and conditions for copying, distribution and modification -follow. - -TERMS AND CONDITIONS -0. Definitions. -"This License" refers to version 3 of the GNU Affero General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this License. -Each licensee is addressed as "you". "Licensees" and "recipients" may be -individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work in a -fashion requiring copyright permission, other than the making of an exact -copy. The resulting work is called a "modified version" of the earlier work -or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based on the -Program. - -To "propagate" a work means to do anything with it that, without permission, -would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a -private copy. Propagation includes copying, distribution (with or without -modification), making available to the public, and in some countries other -activities as well. - -To "convey" a work means any kind of propagation that enables other parties -to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" to the -extent that it includes a convenient and prominently visible feature that (1) -displays an appropriate copyright notice, and (2) tells the user that there -is no warranty for the work (except to the extent that warranties are -provided), that licensees may convey the work under this License, and how to -view a copy of this License. If the interface presents a list of user -commands or options, such as a menu, a prominent item in the list meets this -criterion. - -1. Source Code. -The "source code" for a work means the preferred form of the work for making -modifications to it. "Object code" means any non-source form of a work. - -A "Standard Interface" means an interface that either is an official standard -defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used -among developers working in that language. - -The "System Libraries" of an executable work include anything, other than the -work as a whole, that (a) is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and (b) serves only -to enable use of the work with that Major Component, or to implement a -Standard Interface for which an implementation is available to the public in -source code form. A "Major Component", in this context, means a major -essential component (kernel, window system, and so on) of the specific -operating system (if any) on which the executable work runs, or a compiler -used to produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the -object code and to modify the work, including scripts to control those -activities. However, it does not include the work's System Libraries, or -general-purpose tools or generally available free programs which are used -unmodified in performing those activities but which are not part of the work. -For example, Corresponding Source includes interface definition files -associated with source files for the work, and the source code for shared -libraries and dynamically linked subprograms that the work is specifically -designed to require, such as by intimate data communication or control flow -between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -2. Basic Permissions. -All rights granted under this License are granted for the term of copyright -on the Program, and are irrevocable provided the stated conditions are met. -This License explicitly affirms your unlimited permission to run the -unmodified Program. The output from running a covered work is covered by this -License only if the output, given its content, constitutes a covered work. -This License acknowledges your rights of fair use or other equivalent, as -provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey -covered works to others for the sole purpose of having them make -modifications exclusively for you, or provide you with facilities for running -those works, provided that you comply with the terms of this License in -conveying all material for which you do not control copyright. Those thus -making or running the covered works for you must do so exclusively on your -behalf, under your direction and control, on terms that prohibit them from -making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes it -unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. -No covered work shall be deemed part of an effective technological measure -under any applicable law fulfilling obligations under article 11 of the WIPO -copyright treaty adopted on 20 December 1996, or similar laws prohibiting or -restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention is -effected by exercising rights under this License with respect to the covered -work, and you disclaim any intention to limit operation or modification of -the work as a means of enforcing, against the work's users, your or third -parties' legal rights to forbid circumvention of technological measures. - -4. Conveying Verbatim Copies. -You may convey verbatim copies of the Program's source code as you receive -it, in any medium, provided that you conspicuously and appropriately publish -on each copy an appropriate copyright notice; keep intact all notices stating -that this License and any non-permissive terms added in accord with section 7 -apply to the code; keep intact all notices of the absence of any warranty; -and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you -may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. -You may convey a work based on the Program, or the modifications to produce -it from the Program, in the form of source code under the terms of section 4, -provided that you also meet all of these conditions: - -a) The work must carry prominent notices stating that you modified it, and -giving a relevant date. -b) The work must carry prominent notices stating that it is released under -this License and any conditions added under section 7. This requirement -modifies the requirement in section 4 to "keep intact all notices". -c) You must license the entire work, as a whole, under this License to anyone -who comes into possession of a copy. This License will therefore apply, along -with any applicable section 7 additional terms, to the whole of the work, and -all its parts, regardless of how they are packaged. This License gives no -permission to license the work in any other way, but it does not invalidate -such permission if you have separately received it. -d) If the work has interactive user interfaces, each must display Appropriate -Legal Notices; however, if the Program has interactive interfaces that do not -display Appropriate Legal Notices, your work need not make them do so. -A compilation of a covered work with other separate and independent works, -which are not by their nature extensions of the covered work, and which are -not combined with it such as to form a larger program, in or on a volume of a -storage or distribution medium, is called an "aggregate" if the compilation -and its resulting copyright are not used to limit the access or legal rights -of the compilation's users beyond what the individual works permit. Inclusion -of a covered work in an aggregate does not cause this License to apply to the -other parts of the aggregate. - -6. Conveying Non-Source Forms. -You may convey a covered work in object code form under the terms of sections -4 and 5, provided that you also convey the machine-readable Corresponding -Source under the terms of this License, in one of these ways: - -a) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed -on a durable physical medium customarily used for software interchange. -b) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at -least three years and valid for as long as you offer spare parts or customer -support for that product model, to give anyone who possesses the object code -either (1) a copy of the Corresponding Source for all the software in the -product that is covered by this License, on a durable physical medium -customarily used for software interchange, for a price no more than your -reasonable cost of physically performing this conveying of source, or (2) -access to copy the Corresponding Source from a network server at no charge. -c) Convey individual copies of the object code with a copy of the written -offer to provide the Corresponding Source. This alternative is allowed only -occasionally and noncommercially, and only if you received the object code -with such an offer, in accord with subsection 6b. -d) Convey the object code by offering access from a designated place (gratis -or for a charge), and offer equivalent access to the Corresponding Source in -the same way through the same place at no further charge. You need not -require recipients to copy the Corresponding Source along with the object -code. If the place to copy the object code is a network server, the -Corresponding Source may be on a different server (operated by you or a third -party) that supports equivalent copying facilities, provided you maintain -clear directions next to the object code saying where to find the -Corresponding Source. Regardless of what server hosts the Corresponding -Source, you remain obligated to ensure that it is available for as long as -needed to satisfy these requirements. -e) Convey the object code using peer-to-peer transmission, provided you -inform other peers where the object code and Corresponding Source of the work -are being offered to the general public at no charge under subsection 6d. -A separable portion of the object code, whose source code is excluded from -the Corresponding Source as a System Library, need not be included in -conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any tangible -personal property which is normally used for personal, family, or household -purposes, or (2) anything designed or sold for incorporation into a dwelling. -In determining whether a product is a consumer product, doubtful cases shall -be resolved in favor of coverage. For a particular product received by a -particular user, "normally used" refers to a typical or common use of that -class of product, regardless of the status of the particular user or of the -way in which the particular user actually uses, or expects or is expected to -use, the product. A product is a consumer product regardless of whether the -product has substantial commercial, industrial or non-consumer uses, unless -such uses represent the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, procedures, -authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified -version of its Corresponding Source. The information must suffice to ensure -that the continued functioning of the modified object code is in no case -prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as part of -a transaction in which the right of possession and use of the User Product is -transferred to the recipient in perpetuity or for a fixed term (regardless of -how the transaction is characterized), the Corresponding Source conveyed -under this section must be accompanied by the Installation Information. But -this requirement does not apply if neither you nor any third party retains -the ability to install modified object code on the User Product (for example, -the work has been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates for -a work that has been modified or installed by the recipient, or for the User -Product in which it has been modified or installed. Access to a network may -be denied when the modification itself materially and adversely affects the -operation of the network or violates the rules and protocols for -communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in -accord with this section must be in a format that is publicly documented (and -with an implementation available to the public in source code form), and must -require no special password or key for unpacking, reading or copying. - -7. Additional Terms. -"Additional permissions" are terms that supplement the terms of this License -by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as -though they were included in this License, to the extent that they are valid -under applicable law. If additional permissions apply only to part of the -Program, that part may be used separately under those permissions, but the -entire Program remains governed by this License without regard to the -additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when -you modify the work.) You may place additional permissions on material, added -by you to a covered work, for which you have or can give appropriate -copyright permission. - -Notwithstanding any other provision of this License, for material you add to -a covered work, you may (if authorized by the copyright holders of that -material) supplement the terms of this License with terms: - -a) Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -b) Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed -by works containing it; or -c) Prohibiting misrepresentation of the origin of that material, or requiring -that modified versions of such material be marked in reasonable ways as -different from the original version; or -d) Limiting the use for publicity purposes of names of licensors or authors -of the material; or -e) Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -f) Requiring indemnification of licensors and authors of that material by -anyone who conveys the material (or modified versions of it) with contractual -assumptions of liability to the recipient, for any liability that these -contractual assumptions directly impose on those licensors and authors. -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is governed -by this License along with a term that is a further restriction, you may -remove that term. If a license document contains a further restriction but -permits relicensing or conveying under this License, you may add to a covered -work material governed by the terms of that license document, provided that -the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must -place, in the relevant source files, a statement of the additional terms that -apply to those files, or a notice indicating where to find the applicable -terms. - -Additional terms, permissive or non-permissive, may be stated in the form of -a separately written license, or stated as exceptions; the above requirements -apply either way. - -8. Termination. -You may not propagate or modify a covered work except as expressly provided -under this License. Any attempt otherwise to propagate or modify it is void, -and will automatically terminate your rights under this License (including -any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated (a) provisionally, unless and until -the copyright holder explicitly and finally terminates your license, and (b) -permanently, if the copyright holder fails to notify you of the violation by -some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated -permanently if the copyright holder notifies you of the violation by some -reasonable means, this is the first time you have received notice of -violation of this License (for any work) from that copyright holder, and you -cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses -of parties who have received copies or rights from you under this License. If -your rights have been terminated and not permanently reinstated, you do not -qualify to receive new licenses for the same material under section 10. - -9. Acceptance Not Required for Having Copies. -You are not required to accept this License in order to receive or run a copy -of the Program. Ancillary propagation of a covered work occurring solely as a -consequence of using peer-to-peer transmission to receive a copy likewise -does not require acceptance. However, nothing other than this License grants -you permission to propagate or modify any covered work. These actions -infringe copyright if you do not accept this License. Therefore, by modifying -or propagating a covered work, you indicate your acceptance of this License -to do so. - -10. Automatic Licensing of Downstream Recipients. -Each time you convey a covered work, the recipient automatically receives a -license from the original licensors, to run, modify and propagate that work, -subject to this License. You are not responsible for enforcing compliance by -third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered work -results from an entity transaction, each party to that transaction who -receives a copy of the work also receives whatever licenses to the work the -party's predecessor in interest had or could give under the previous -paragraph, plus a right to possession of the Corresponding Source of the work -from the predecessor in interest, if the predecessor has it or can get it -with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights -granted or affirmed under this License. For example, you may not impose a -license fee, royalty, or other charge for exercise of rights granted under -this License, and you may not initiate litigation (including a cross-claim or -counterclaim in a lawsuit) alleging that any patent claim is infringed by -making, using, selling, offering for sale, or importing the Program or any -portion of it. - -11. Patents. -A "contributor" is a copyright holder who authorizes use under this License -of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter -acquired, that would be infringed by some manner, permitted by this License, -of making, using, or selling its contributor version, but do not include -claims that would be infringed only as a consequence of further modification -of the contributor version. For purposes of this definition, "control" -includes the right to grant patent sublicenses in a manner consistent with -the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent -license under the contributor's essential patent claims, to make, use, sell, -offer for sale, import and otherwise run, modify and propagate the contents -of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent (such -as an express permission to practice a patent or covenant not to sue for -patent infringement). To "grant" such a patent license to a party means to -make such an agreement or commitment not to enforce a patent against the -party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of -charge and under the terms of this License, through a publicly available -network server or other readily accessible means, then you must either (1) -cause the Corresponding Source to be so available, or (2) arrange to deprive -yourself of the benefit of the patent license for this particular work, or -(3) arrange, in a manner consistent with the requirements of this License, to -extend the patent license to downstream recipients. "Knowingly relying" means -you have actual knowledge that, but for the patent license, your conveying -the covered work in a country, or your recipient's use of the covered work in -a country, would infringe one or more identifiable patents in that country -that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, -you convey, or propagate by procuring conveyance of, a covered work, and -grant a patent license to some of the parties receiving the covered work -authorizing them to use, propagate, modify or convey a specific copy of the -covered work, then the patent license you grant is automatically extended to -all recipients of the covered work and works based on it. - -A patent license is "discriminatory" if it does not include within the scope -of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under -this License. You may not convey a covered work if you are a party to an -arrangement with a third party that is in the business of distributing -software, under which you make payment to the third party based on the extent -of your activity of conveying the work, and under which the third party -grants, to any of the parties who would receive the covered work from you, a -discriminatory patent license (a) in connection with copies of the covered -work conveyed by you (or copies made from those copies), or (b) primarily for -and in connection with specific products or compilations that contain the -covered work, unless you entered into that arrangement, or that patent -license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any -implied license or other defenses to infringement that may otherwise be -available to you under applicable patent law. - -12. No Surrender of Others' Freedom. -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not excuse -you from the conditions of this License. If you cannot convey a covered work -so as to satisfy simultaneously your obligations under this License and any -other pertinent obligations, then as a consequence you may not convey it at -all. For example, if you agree to terms that obligate you to collect a -royalty for further conveying from those to whom you convey the Program, the -only way you could satisfy both those terms and this License would be to -refrain entirely from conveying the Program. - -13. Remote Network Interaction; Use with the GNU General Public License. -Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users interacting -with it remotely through a computer network (if your version supports such -interaction) an opportunity to receive the Corresponding Source of your -version by providing access to the Corresponding Source from a network server -at no charge, through some standard or customary means of facilitating -copying of software. This Corresponding Source shall include the -Corresponding Source for any work covered by version 3 of the GNU General -Public License that is incorporated pursuant to the following paragraph. - -Notwithstanding any other provision of this License, you have permission to -link or combine any covered work with a work licensed under version 3 of the -GNU General Public License into a single combined work, and to convey the -resulting work. The terms of this License will continue to apply to the part -which is the covered work, but the work with which it is combined will remain -governed by version 3 of the GNU General Public License. - -14. Revised Versions of this License. -The Free Software Foundation may publish revised and/or new versions of the -GNU Affero General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU Affero General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or of any -later version published by the Free Software Foundation. If the Program does -not specify a version number of the GNU Affero General Public License, you -may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the -GNU Affero General Public License can be used, that proxy's public statement -of acceptance of a version permanently authorizes you to choose that version -for the Program. - -Later license versions may give you additional or different permissions. -However, no additional obligations are imposed on any author or copyright -holder as a result of your choosing to follow a later version. - -15. Disclaimer of Warranty. -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE -LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, -EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. -SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY -SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL -ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE -PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE -OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR -DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR -A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH -HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. -If the disclaimer of warranty and limitation of liability provided above -cannot be given local legal effect according to their terms, reviewing courts -shall apply local law that most closely approximates an absolute waiver of -all civil liability in connection with the Program, unless a warranty or -assumption of liability accompanies a copy of the Program in return for a -fee. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Programs -If you develop a new program, and you want it to be of the greatest possible -use to the public, the best way to achieve this is to make it free software -which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach -them to the start of each source file to most effectively state the exclusion -of warranty; and each file should have at least the "copyright" line and a -pointer to where the full notice is found. - -SpacetimeDB: A database which replaces your server. -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -Also add information on how to contact you by electronic and paper mail. - -If your software can interact with users remotely through a computer network, -you should also make sure that it provides a way for users to get its source. -For example, if your program is a web application, its interface could -display a "Source" link that leads users to an archive of the code. There are -many ways you could offer source, and different solutions will be better for -different programs; see section 13 for the specific requirements. - -You should also get your employer (if you work as a programmer) or school, if -any, to sign a "copyright disclaimer" for the program, if necessary. For more -information on this, and how to apply and follow the GNU AGPL, see -. + 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 index 5fa33c4dfd9..17bbd500788 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -5,7 +5,7 @@ Fixed-window rate limiter submodule for SpacetimeDB TypeScript modules. ## Install ```bash -npm install @spacetimedb/rate-limit spacetimedb@^2.8.3 +npm install @spacetimedb/rate-limit spacetimedb ``` Requires SpacetimeDB 2.8.3 or later for submodule mounting. @@ -149,4 +149,4 @@ pnpm run typecheck ## License -[BUSL-1.1](./LICENSE.txt) - same as SpacetimeDB. +[Apache-2.0](./LICENSE.txt). diff --git a/spacetime-rate-limit-ts/example/README.md b/spacetime-rate-limit-ts/example/README.md index 0701813bd2c..1db70b7ddf7 100644 --- a/spacetime-rate-limit-ts/example/README.md +++ b/spacetime-rate-limit-ts/example/README.md @@ -60,7 +60,7 @@ This workspace tests the submodule source in this repository. Consumer applications install the published release: ```bash -npm install @spacetimedb/rate-limit spacetimedb@^2.8.3 +npm install @spacetimedb/rate-limit spacetimedb ``` Follow the package's diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts index 06e1d241db6..5817b1b1baa 100644 --- a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts @@ -548,7 +548,7 @@ export const rateLimitEventsAdmin = spacetimedb.view( : [] ); -export const start_reactor = spacetimedb.procedure( +export const startReactor = spacetimedb.procedure( {}, reactorActionResult, ctx => { @@ -562,7 +562,7 @@ export const start_reactor = spacetimedb.procedure( } ); -export const tap_reactor = spacetimedb.procedure( +export const tapReactor = spacetimedb.procedure( {}, reactorActionResult, ctx => { @@ -799,7 +799,7 @@ export const overcharge = spacetimedb.procedure( } ); -export const buy_upgrade = spacetimedb.procedure( +export const buyUpgrade = spacetimedb.procedure( { upgradeId: t.string() }, reactorActionResult, (ctx, args) => { @@ -931,7 +931,7 @@ export const buy_upgrade = spacetimedb.procedure( } ); -export const repair_reactor = spacetimedb.procedure( +export const repairReactor = spacetimedb.procedure( {}, reactorActionResult, ctx => { @@ -1060,7 +1060,7 @@ export const runSweep = spacetimedb.procedure( } ); -export const set_player_color = spacetimedb.reducer( +export const setPlayerColor = spacetimedb.reducer( { color: t.string() }, (ctx, args) => { const color = requirePlayerColor(args.color); @@ -1116,7 +1116,7 @@ export const updateConfig = spacetimedb.reducer( } ); -export const rate_limit_demo_sweep = spacetimedb.reducer( +export const rateLimitDemoSweep = spacetimedb.reducer( { onSchedule: rateLimitDemoSweepTick }, { arg: rateLimitDemoSweepTick.rowType }, (ctx, _args) => { diff --git a/spacetime-rate-limit-ts/package.json b/spacetime-rate-limit-ts/package.json index c828b291e19..103fdd58762 100644 --- a/spacetime-rate-limit-ts/package.json +++ b/spacetime-rate-limit-ts/package.json @@ -2,7 +2,7 @@ "name": "@spacetimedb/rate-limit", "description": "Fixed-window rate limiting and bounded expiration sweeps for SpacetimeDB TypeScript modules.", "version": "0.1.0", - "license": "BUSL-1.1", + "license": "Apache-2.0", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/spacetime-rate-limit-ts/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/spacetimedb/src/index.ts index c11828b0c59..c057c30f4a0 100644 --- a/spacetime-rate-limit-ts/spacetimedb/src/index.ts +++ b/spacetime-rate-limit-ts/spacetimedb/src/index.ts @@ -4,7 +4,7 @@ export { adminRateLimitBuckets, addRateLimitAdmin, consume, - rate_limit_sweep, + rateLimitSweep, resetBuckets, runSweep, updateConfig, diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts index d7a2c306a72..ed5e49da5c2 100644 --- a/spacetime-rate-limit-ts/src/submodule.ts +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -21,7 +21,7 @@ export { adminRateLimitBuckets, addRateLimitAdmin, consume, - rate_limit_sweep, + rateLimitSweep, resetBuckets, runSweep, updateConfig, diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts index bda705dcaad..6a3c3d88d5b 100644 --- a/spacetime-rate-limit-ts/src/submodule/operations.ts +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -179,7 +179,7 @@ export const adminRateLimitBuckets = spacetimedb.view( } ); -export const rate_limit_sweep = spacetimedb.reducer( +export const rateLimitSweep = spacetimedb.reducer( { onSchedule: rateLimitSweepTick }, { arg: rateLimitSweepTick.rowType }, (ctx, _args) => { diff --git a/spacetime-retry-ts/LICENSE.txt b/spacetime-retry-ts/LICENSE.txt index ea0cb1c5e9e..4e61a2122e7 100644 --- a/spacetime-retry-ts/LICENSE.txt +++ b/spacetime-retry-ts/LICENSE.txt @@ -1,759 +1,201 @@ -SPACETIMEDB BUSINESS SOURCE LICENSE AGREEMENT - -Business Source License 1.1 - -Parameters - -Licensor: Clockwork Laboratories, Inc. -Licensed Work: SpacetimeDB 2.8.3 - The Licensed Work is - (c) 2023 Clockwork Laboratories, Inc. - -Additional Use Grant: You may make use of the Licensed Work provided your - application or service uses the Licensed Work with no - more than one SpacetimeDB instance in production and - provided that you do not use the Licensed Work for a - Database Service. - - A “Database Service” is a commercial offering that - allows third parties (other than your employees and - contractors) to access the functionality of the - Licensed Work by creating tables whose schemas are - controlled by such third parties. - -Change Date: 2031-08-18 - -Change License: GNU Affero General Public License v3.0 with a linking - exception - -For information about alternative licensing arrangements for the Software, -please visit: https://spacetimedb.com - -Notice - -The Business Source License (this document, or the “License”) is not an Open -Source license. However, the Licensed Work will eventually be made available -under an Open Source License, as stated in this License. - -License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. -“Business Source License” is a trademark of MariaDB Corporation Ab. - ------------------------------------------------------------------------------ - -Base License and Subdirectory Specific Licenses - -1. Repository-Wide License -Except as provided in Section 2 below, the contents of this repository are licensed under the Business Source License (“BSL”), which includes a change date resulting in a licensing change to the GNU Affero General Public License v3.0 with Linking Exception on that date. See the full text of the BSL and AGPL with Linking Exception in this file below. - -2. Subdirectory-Specific Licenses -Certain subdirectories within this repository are licensed under different terms. - -If a subdirectory contains its own LICENSE or LICENSE.txt file, the terms in that file apply exclusively to all files and subfolders within that subdirectory. - -In the event of any conflict between this base license and a subdirectory’s license, the base license will govern for that subdirectory’s contents. - -3. Contributor Acknowledgement -By contributing to this repository, you agree that: - -Your contributions will be licensed under the license applicable to the directory or subdirectory in which your contribution is made. - -If you contribute to multiple subdirectories, the applicable license for each subdirectory will apply to your contributions in that subdirectory. - -4. Reading the Applicable License -Before using, modifying, or distributing code from this repository, you must read: - -This base LICENSE.txt file for the overall repository license. - -Any LICENSE or LICENSE.txt file in a subdirectory that you intend to use or contribute to. - ------------------------------------------------------------------------------ - -Business Source License 1.1 - -Terms - -The Licensor hereby grants you the right to copy, modify, create derivative -works, redistribute, and make non-production use of the Licensed Work. The -Licensor may make an Additional Use Grant, above, permitting limited -production use. - -Effective on the Change Date, or the fourth anniversary of the first publicly -available distribution of a specific version of the Licensed Work under this -License, whichever comes first, the Licensor hereby grants you rights under -the terms of the Change License, and the rights granted in the paragraph -above terminate. - -If your use of the Licensed Work does not comply with the requirements -currently in effect as described in this License, you must purchase a -commercial license from the Licensor, its affiliated entities, or authorized -resellers, or you must refrain from using the Licensed Work. - -All copies of the original and modified Licensed Work, and derivative works -of the Licensed Work, are subject to this License. This License applies -separately for each version of the Licensed Work and the Change Date may vary -for each version of the Licensed Work released by Licensor. - -You must conspicuously display this License on each original or modified copy -of the Licensed Work. If you receive the Licensed Work in original or -modified form from a third party, the terms and conditions set forth in this -License apply to your use of that work. - -Any use of the Licensed Work in violation of this License will automatically -terminate your rights under this License for the current and all other -versions of the Licensed Work. - -This License does not grant you any right in any trademark or logo of -Licensor or its affiliates (provided that you may use a trademark or logo of -Licensor as expressly required by this License). - -TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON -AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, -EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND -TITLE. - -MariaDB hereby grants you permission to use this License’s text to license -your works, and to refer to it using the trademark “Business Source License”, -as long as you comply with the Covenants of Licensor below. - -Covenants of Licensor - -In consideration of the right to use this License’s text and the “Business -Source License” name and trademark, Licensor covenants to MariaDB, and to all -other recipients of the licensed work to be provided by Licensor: - -1. To specify as the Change License the GPL Version 2.0 or any later version, - or a license that is compatible with GPL Version 2.0 or a later version, - where “compatible” means that software provided under the Change License can - be included in a program with software provided under GPL Version 2.0 or a - later version. Licensor may specify additional Change Licenses without - limitation. - -2. To either: (a) specify an additional grant of rights to use that does not - impose any additional restriction on the right granted in this License, as - the Additional Use Grant; or (b) insert the text “None”. - -3. To specify a Change Date. - -4. Not to modify this License in any other way. - ------------------------------------------------------------------------------ - -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify it under -the terms of the GNU Affero General Public License, version 3, as published -by the Free Software Foundation. - -This program is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -details. - -You should have received a copy of the GNU Affero General Public License -along with this program; if not, see . - -Additional permission under GNU GPL version 3 section 7 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission to convey the resulting work. - -Additional permission under GNU AGPL version 3 section 13 - -If you modify this Program, or any covered work, by linking or combining it -with SpacetimeDB (or a modified version of that library), containing parts -covered by the terms of the AGPL v3.0, the licensors of this Program grant -you additional permission that, notwithstanding any other provision of this -License, you need not prominently offer all users interacting with your -modified version remotely through a computer network an opportunity to -receive the Corresponding Source of your version from a network server at no -charge, if your version supports such interaction. This permission does not -waive or modify any other obligations or terms of the AGPL v3.0, except for -the specific requirement set forth in section 13. - -A copy of the AGPL v3.0 license is reproduced below. - - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - -Copyright © 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -Preamble -The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - -The licenses for most software and other practical works are designed to take -away your freedom to share and change the works. By contrast, our General -Public Licenses are intended to guarantee your freedom to share and change -all versions of a program--to make sure it remains free software for all its -users. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom -to distribute copies of free software (and charge for them if you wish), that -you receive source code or can get it if you want it, that you can change the -software or use pieces of it in new free programs, and that you know you can -do these things. - -Developers that use our General Public Licenses protect your rights with two -steps: (1) assert copyright on the software, and (2) offer you this License -which gives you legal permission to copy, distribute and/or modify the -software. - -A secondary benefit of defending all users' freedom is that improvements made -in alternate versions of the program, if they receive widespread use, become -available for other developers to incorporate. Many developers of free -software are heartened and encouraged by the resulting cooperation. However, -in the case of software used on network servers, this result may fail to come -about. The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its source -code to the public. - -The GNU Affero General Public License is designed specifically to ensure -that, in such cases, the modified source code becomes available to the -community. It requires the operator of a network server to provide the source -code of the modified version running there to the users of that server. -Therefore, public use of a modified version, on a publicly accessible server, -gives the public access to the source code of the modified version. - -An older license, called the Affero General Public License and published by -Affero, was designed to accomplish similar goals. This is a different -license, not a version of the Affero GPL, but Affero has released a new -version of the Affero GPL which permits relicensing under this license. - -The precise terms and conditions for copying, distribution and modification -follow. - -TERMS AND CONDITIONS -0. Definitions. -"This License" refers to version 3 of the GNU Affero General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this License. -Each licensee is addressed as "you". "Licensees" and "recipients" may be -individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work in a -fashion requiring copyright permission, other than the making of an exact -copy. The resulting work is called a "modified version" of the earlier work -or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based on the -Program. - -To "propagate" a work means to do anything with it that, without permission, -would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a -private copy. Propagation includes copying, distribution (with or without -modification), making available to the public, and in some countries other -activities as well. - -To "convey" a work means any kind of propagation that enables other parties -to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" to the -extent that it includes a convenient and prominently visible feature that (1) -displays an appropriate copyright notice, and (2) tells the user that there -is no warranty for the work (except to the extent that warranties are -provided), that licensees may convey the work under this License, and how to -view a copy of this License. If the interface presents a list of user -commands or options, such as a menu, a prominent item in the list meets this -criterion. - -1. Source Code. -The "source code" for a work means the preferred form of the work for making -modifications to it. "Object code" means any non-source form of a work. - -A "Standard Interface" means an interface that either is an official standard -defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used -among developers working in that language. - -The "System Libraries" of an executable work include anything, other than the -work as a whole, that (a) is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and (b) serves only -to enable use of the work with that Major Component, or to implement a -Standard Interface for which an implementation is available to the public in -source code form. A "Major Component", in this context, means a major -essential component (kernel, window system, and so on) of the specific -operating system (if any) on which the executable work runs, or a compiler -used to produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the -object code and to modify the work, including scripts to control those -activities. However, it does not include the work's System Libraries, or -general-purpose tools or generally available free programs which are used -unmodified in performing those activities but which are not part of the work. -For example, Corresponding Source includes interface definition files -associated with source files for the work, and the source code for shared -libraries and dynamically linked subprograms that the work is specifically -designed to require, such as by intimate data communication or control flow -between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -2. Basic Permissions. -All rights granted under this License are granted for the term of copyright -on the Program, and are irrevocable provided the stated conditions are met. -This License explicitly affirms your unlimited permission to run the -unmodified Program. The output from running a covered work is covered by this -License only if the output, given its content, constitutes a covered work. -This License acknowledges your rights of fair use or other equivalent, as -provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey -covered works to others for the sole purpose of having them make -modifications exclusively for you, or provide you with facilities for running -those works, provided that you comply with the terms of this License in -conveying all material for which you do not control copyright. Those thus -making or running the covered works for you must do so exclusively on your -behalf, under your direction and control, on terms that prohibit them from -making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes it -unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. -No covered work shall be deemed part of an effective technological measure -under any applicable law fulfilling obligations under article 11 of the WIPO -copyright treaty adopted on 20 December 1996, or similar laws prohibiting or -restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention is -effected by exercising rights under this License with respect to the covered -work, and you disclaim any intention to limit operation or modification of -the work as a means of enforcing, against the work's users, your or third -parties' legal rights to forbid circumvention of technological measures. - -4. Conveying Verbatim Copies. -You may convey verbatim copies of the Program's source code as you receive -it, in any medium, provided that you conspicuously and appropriately publish -on each copy an appropriate copyright notice; keep intact all notices stating -that this License and any non-permissive terms added in accord with section 7 -apply to the code; keep intact all notices of the absence of any warranty; -and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you -may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. -You may convey a work based on the Program, or the modifications to produce -it from the Program, in the form of source code under the terms of section 4, -provided that you also meet all of these conditions: - -a) The work must carry prominent notices stating that you modified it, and -giving a relevant date. -b) The work must carry prominent notices stating that it is released under -this License and any conditions added under section 7. This requirement -modifies the requirement in section 4 to "keep intact all notices". -c) You must license the entire work, as a whole, under this License to anyone -who comes into possession of a copy. This License will therefore apply, along -with any applicable section 7 additional terms, to the whole of the work, and -all its parts, regardless of how they are packaged. This License gives no -permission to license the work in any other way, but it does not invalidate -such permission if you have separately received it. -d) If the work has interactive user interfaces, each must display Appropriate -Legal Notices; however, if the Program has interactive interfaces that do not -display Appropriate Legal Notices, your work need not make them do so. -A compilation of a covered work with other separate and independent works, -which are not by their nature extensions of the covered work, and which are -not combined with it such as to form a larger program, in or on a volume of a -storage or distribution medium, is called an "aggregate" if the compilation -and its resulting copyright are not used to limit the access or legal rights -of the compilation's users beyond what the individual works permit. Inclusion -of a covered work in an aggregate does not cause this License to apply to the -other parts of the aggregate. - -6. Conveying Non-Source Forms. -You may convey a covered work in object code form under the terms of sections -4 and 5, provided that you also convey the machine-readable Corresponding -Source under the terms of this License, in one of these ways: - -a) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed -on a durable physical medium customarily used for software interchange. -b) Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at -least three years and valid for as long as you offer spare parts or customer -support for that product model, to give anyone who possesses the object code -either (1) a copy of the Corresponding Source for all the software in the -product that is covered by this License, on a durable physical medium -customarily used for software interchange, for a price no more than your -reasonable cost of physically performing this conveying of source, or (2) -access to copy the Corresponding Source from a network server at no charge. -c) Convey individual copies of the object code with a copy of the written -offer to provide the Corresponding Source. This alternative is allowed only -occasionally and noncommercially, and only if you received the object code -with such an offer, in accord with subsection 6b. -d) Convey the object code by offering access from a designated place (gratis -or for a charge), and offer equivalent access to the Corresponding Source in -the same way through the same place at no further charge. You need not -require recipients to copy the Corresponding Source along with the object -code. If the place to copy the object code is a network server, the -Corresponding Source may be on a different server (operated by you or a third -party) that supports equivalent copying facilities, provided you maintain -clear directions next to the object code saying where to find the -Corresponding Source. Regardless of what server hosts the Corresponding -Source, you remain obligated to ensure that it is available for as long as -needed to satisfy these requirements. -e) Convey the object code using peer-to-peer transmission, provided you -inform other peers where the object code and Corresponding Source of the work -are being offered to the general public at no charge under subsection 6d. -A separable portion of the object code, whose source code is excluded from -the Corresponding Source as a System Library, need not be included in -conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any tangible -personal property which is normally used for personal, family, or household -purposes, or (2) anything designed or sold for incorporation into a dwelling. -In determining whether a product is a consumer product, doubtful cases shall -be resolved in favor of coverage. For a particular product received by a -particular user, "normally used" refers to a typical or common use of that -class of product, regardless of the status of the particular user or of the -way in which the particular user actually uses, or expects or is expected to -use, the product. A product is a consumer product regardless of whether the -product has substantial commercial, industrial or non-consumer uses, unless -such uses represent the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, procedures, -authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified -version of its Corresponding Source. The information must suffice to ensure -that the continued functioning of the modified object code is in no case -prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as part of -a transaction in which the right of possession and use of the User Product is -transferred to the recipient in perpetuity or for a fixed term (regardless of -how the transaction is characterized), the Corresponding Source conveyed -under this section must be accompanied by the Installation Information. But -this requirement does not apply if neither you nor any third party retains -the ability to install modified object code on the User Product (for example, -the work has been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates for -a work that has been modified or installed by the recipient, or for the User -Product in which it has been modified or installed. Access to a network may -be denied when the modification itself materially and adversely affects the -operation of the network or violates the rules and protocols for -communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in -accord with this section must be in a format that is publicly documented (and -with an implementation available to the public in source code form), and must -require no special password or key for unpacking, reading or copying. - -7. Additional Terms. -"Additional permissions" are terms that supplement the terms of this License -by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as -though they were included in this License, to the extent that they are valid -under applicable law. If additional permissions apply only to part of the -Program, that part may be used separately under those permissions, but the -entire Program remains governed by this License without regard to the -additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when -you modify the work.) You may place additional permissions on material, added -by you to a covered work, for which you have or can give appropriate -copyright permission. - -Notwithstanding any other provision of this License, for material you add to -a covered work, you may (if authorized by the copyright holders of that -material) supplement the terms of this License with terms: - -a) Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -b) Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed -by works containing it; or -c) Prohibiting misrepresentation of the origin of that material, or requiring -that modified versions of such material be marked in reasonable ways as -different from the original version; or -d) Limiting the use for publicity purposes of names of licensors or authors -of the material; or -e) Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -f) Requiring indemnification of licensors and authors of that material by -anyone who conveys the material (or modified versions of it) with contractual -assumptions of liability to the recipient, for any liability that these -contractual assumptions directly impose on those licensors and authors. -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is governed -by this License along with a term that is a further restriction, you may -remove that term. If a license document contains a further restriction but -permits relicensing or conveying under this License, you may add to a covered -work material governed by the terms of that license document, provided that -the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must -place, in the relevant source files, a statement of the additional terms that -apply to those files, or a notice indicating where to find the applicable -terms. - -Additional terms, permissive or non-permissive, may be stated in the form of -a separately written license, or stated as exceptions; the above requirements -apply either way. - -8. Termination. -You may not propagate or modify a covered work except as expressly provided -under this License. Any attempt otherwise to propagate or modify it is void, -and will automatically terminate your rights under this License (including -any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated (a) provisionally, unless and until -the copyright holder explicitly and finally terminates your license, and (b) -permanently, if the copyright holder fails to notify you of the violation by -some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated -permanently if the copyright holder notifies you of the violation by some -reasonable means, this is the first time you have received notice of -violation of this License (for any work) from that copyright holder, and you -cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses -of parties who have received copies or rights from you under this License. If -your rights have been terminated and not permanently reinstated, you do not -qualify to receive new licenses for the same material under section 10. - -9. Acceptance Not Required for Having Copies. -You are not required to accept this License in order to receive or run a copy -of the Program. Ancillary propagation of a covered work occurring solely as a -consequence of using peer-to-peer transmission to receive a copy likewise -does not require acceptance. However, nothing other than this License grants -you permission to propagate or modify any covered work. These actions -infringe copyright if you do not accept this License. Therefore, by modifying -or propagating a covered work, you indicate your acceptance of this License -to do so. - -10. Automatic Licensing of Downstream Recipients. -Each time you convey a covered work, the recipient automatically receives a -license from the original licensors, to run, modify and propagate that work, -subject to this License. You are not responsible for enforcing compliance by -third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered work -results from an entity transaction, each party to that transaction who -receives a copy of the work also receives whatever licenses to the work the -party's predecessor in interest had or could give under the previous -paragraph, plus a right to possession of the Corresponding Source of the work -from the predecessor in interest, if the predecessor has it or can get it -with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights -granted or affirmed under this License. For example, you may not impose a -license fee, royalty, or other charge for exercise of rights granted under -this License, and you may not initiate litigation (including a cross-claim or -counterclaim in a lawsuit) alleging that any patent claim is infringed by -making, using, selling, offering for sale, or importing the Program or any -portion of it. - -11. Patents. -A "contributor" is a copyright holder who authorizes use under this License -of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter -acquired, that would be infringed by some manner, permitted by this License, -of making, using, or selling its contributor version, but do not include -claims that would be infringed only as a consequence of further modification -of the contributor version. For purposes of this definition, "control" -includes the right to grant patent sublicenses in a manner consistent with -the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent -license under the contributor's essential patent claims, to make, use, sell, -offer for sale, import and otherwise run, modify and propagate the contents -of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent (such -as an express permission to practice a patent or covenant not to sue for -patent infringement). To "grant" such a patent license to a party means to -make such an agreement or commitment not to enforce a patent against the -party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of -charge and under the terms of this License, through a publicly available -network server or other readily accessible means, then you must either (1) -cause the Corresponding Source to be so available, or (2) arrange to deprive -yourself of the benefit of the patent license for this particular work, or -(3) arrange, in a manner consistent with the requirements of this License, to -extend the patent license to downstream recipients. "Knowingly relying" means -you have actual knowledge that, but for the patent license, your conveying -the covered work in a country, or your recipient's use of the covered work in -a country, would infringe one or more identifiable patents in that country -that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, -you convey, or propagate by procuring conveyance of, a covered work, and -grant a patent license to some of the parties receiving the covered work -authorizing them to use, propagate, modify or convey a specific copy of the -covered work, then the patent license you grant is automatically extended to -all recipients of the covered work and works based on it. - -A patent license is "discriminatory" if it does not include within the scope -of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under -this License. You may not convey a covered work if you are a party to an -arrangement with a third party that is in the business of distributing -software, under which you make payment to the third party based on the extent -of your activity of conveying the work, and under which the third party -grants, to any of the parties who would receive the covered work from you, a -discriminatory patent license (a) in connection with copies of the covered -work conveyed by you (or copies made from those copies), or (b) primarily for -and in connection with specific products or compilations that contain the -covered work, unless you entered into that arrangement, or that patent -license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any -implied license or other defenses to infringement that may otherwise be -available to you under applicable patent law. - -12. No Surrender of Others' Freedom. -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not excuse -you from the conditions of this License. If you cannot convey a covered work -so as to satisfy simultaneously your obligations under this License and any -other pertinent obligations, then as a consequence you may not convey it at -all. For example, if you agree to terms that obligate you to collect a -royalty for further conveying from those to whom you convey the Program, the -only way you could satisfy both those terms and this License would be to -refrain entirely from conveying the Program. - -13. Remote Network Interaction; Use with the GNU General Public License. -Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users interacting -with it remotely through a computer network (if your version supports such -interaction) an opportunity to receive the Corresponding Source of your -version by providing access to the Corresponding Source from a network server -at no charge, through some standard or customary means of facilitating -copying of software. This Corresponding Source shall include the -Corresponding Source for any work covered by version 3 of the GNU General -Public License that is incorporated pursuant to the following paragraph. - -Notwithstanding any other provision of this License, you have permission to -link or combine any covered work with a work licensed under version 3 of the -GNU General Public License into a single combined work, and to convey the -resulting work. The terms of this License will continue to apply to the part -which is the covered work, but the work with which it is combined will remain -governed by version 3 of the GNU General Public License. - -14. Revised Versions of this License. -The Free Software Foundation may publish revised and/or new versions of the -GNU Affero General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU Affero General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or of any -later version published by the Free Software Foundation. If the Program does -not specify a version number of the GNU Affero General Public License, you -may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the -GNU Affero General Public License can be used, that proxy's public statement -of acceptance of a version permanently authorizes you to choose that version -for the Program. - -Later license versions may give you additional or different permissions. -However, no additional obligations are imposed on any author or copyright -holder as a result of your choosing to follow a later version. - -15. Disclaimer of Warranty. -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE -LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, -EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. -SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY -SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL -ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE -PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE -OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR -DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR -A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH -HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. -If the disclaimer of warranty and limitation of liability provided above -cannot be given local legal effect according to their terms, reviewing courts -shall apply local law that most closely approximates an absolute waiver of -all civil liability in connection with the Program, unless a warranty or -assumption of liability accompanies a copy of the Program in return for a -fee. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Programs -If you develop a new program, and you want it to be of the greatest possible -use to the public, the best way to achieve this is to make it free software -which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach -them to the start of each source file to most effectively state the exclusion -of warranty; and each file should have at least the "copyright" line and a -pointer to where the full notice is found. - -SpacetimeDB: A database which replaces your server. -Copyright (C) 2023 Clockwork Laboratories, Inc. - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -Also add information on how to contact you by electronic and paper mail. - -If your software can interact with users remotely through a computer network, -you should also make sure that it provides a way for users to get its source. -For example, if your program is a web application, its interface could -display a "Source" link that leads users to an archive of the code. There are -many ways you could offer source, and different solutions will be better for -different programs; see section 13 for the specific requirements. - -You should also get your employer (if you work as a programmer) or school, if -any, to sign a "copyright disclaimer" for the program, if necessary. For more -information on this, and how to apply and follow the GNU AGPL, see -. + 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 index abfab976ec9..d14685c1f5e 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -7,10 +7,11 @@ dispatch around handlers defined by the host module. ## Install ```bash -npm install @spacetimedb/retry spacetimedb@^2.8.3 +npm install @spacetimedb/retry spacetimedb ``` -Requires SpacetimeDB 2.8.3 or later for submodule mounting. +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. @@ -24,8 +25,7 @@ For the install-to-publish workflow, see 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. Keep the registration casts at this SDK/factory -boundary; application code stays typed through the handler map. +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. @@ -43,7 +43,7 @@ import { const retry = createRetrySubmodule( { table, t, SenderError, ScheduleAt }, { - send_receipt: retryHandler( + sendReceipt: retryHandler( t.object('SendReceiptArgs', { orderId: t.u64() }), (ctx, { orderId }) => { const result = sendReceipt(ctx, orderId); @@ -54,7 +54,7 @@ const retry = createRetrySubmodule( ); const db = schema({ ...retry.tables }); -const retryFire = db.reducer( +export const retryFire = db.reducer( { onSchedule: retry.tables.retryTask }, { arg: retry.tables.retryTask.rowType }, retry.reducers.retryFire @@ -72,6 +72,15 @@ 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 @@ -88,7 +97,7 @@ to Retry administrators: ```ts await conn.reducers.submitRetryTask({ name: `receipt:${orderId}`, - args: { tag: 'send_receipt', value: { orderId } }, + args: { tag: 'SendReceipt', value: { orderId } }, maxAttempts: 5, backoffSecs: 2, }); @@ -101,20 +110,18 @@ screens can subscribe to the factory's admin task and history views. Package entrypoints: - `@spacetimedb/retry/submodule` exports `createRetrySubmodule`. -- `@spacetimedb/retry` exports handler, dispatch, and result helpers. - -The complete factory is available from `./submodule`. +- `@spacetimedb/retry` exports the factory, handler, dispatch, and result helpers. ## Testing ```bash pnpm test pnpm run lint -pnpm run build +pnpm --dir spacetimedb run build ``` -The repository build compiles the local fixture module that mounts the factory. +The build compiles the fixture module that registers the factory's tables and reducers. ## License -BUSL-1.1. See [`LICENSE.txt`](./LICENSE.txt). +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-retry-ts/package.json b/spacetime-retry-ts/package.json index e37077d8579..2e9b188485b 100644 --- a/spacetime-retry-ts/package.json +++ b/spacetime-retry-ts/package.json @@ -2,7 +2,7 @@ "name": "@spacetimedb/retry", "description": "Typed retry dispatch, exponential backoff, and attempt history for SpacetimeDB TypeScript modules.", "version": "0.1.0", - "license": "BUSL-1.1", + "license": "Apache-2.0", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts index d6622d58feb..adae425329d 100644 --- a/spacetime-retry-ts/scripts/test.ts +++ b/spacetime-retry-ts/scripts/test.ts @@ -1,24 +1,21 @@ import * as assert from 'node:assert/strict'; -import type { AlgebraicType } from 'spacetimedb'; -import type { TypeBuilder } from 'spacetimedb/server'; +import { ScheduleAt, Timestamp, t, table } from 'spacetimedb'; import { makeRetryDispatch, retryFailed, retryHandler, retryOk, } from '../src/handler.ts'; - -const fakeBuilder = (): TypeBuilder => - ({}) as unknown as TypeBuilder; +import { createRetrySubmodule } from '../src/submodule.ts'; const calls: string[] = []; const handlers = { - noArgs: retryHandler(fakeBuilder>(), () => { + noArgs: retryHandler(t.unit(), () => { calls.push('noArgs'); return retryOk(); }), withArgs: retryHandler( - fakeBuilder<{ value: string }>(), + t.object('TestArgs', { value: t.string() }), (_ctx, args: { value: string }) => { calls.push(args.value); return retryFailed('try again'); @@ -41,5 +38,82 @@ 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/src/index.ts b/spacetime-retry-ts/spacetimedb/src/index.ts index a6848e82684..2bb9da37e94 100644 --- a/spacetime-retry-ts/spacetimedb/src/index.ts +++ b/spacetime-retry-ts/spacetimedb/src/index.ts @@ -30,6 +30,7 @@ interface FlakyTransaction { const flakyArgs = t.object('FlakyArgs', { taskName: t.string(), succeedAtAttempt: t.u8(), + throwOnFailure: t.bool(), }); const flaky = retryHandler(flakyArgs, (ctx, args): RetryResult => { @@ -37,7 +38,9 @@ const flaky = retryHandler(flakyArgs, (ctx, args): RetryResult => { const task = tx.db.retryTask.name.filter(args.taskName).next().value; const attempt = Number(task?.attempt ?? 0); if (attempt < args.succeedAtAttempt) { - return retryFailed(`simulated failure at attempt ${attempt}`); + const message = `simulated failure at attempt ${attempt}`; + if (args.throwOnFailure) throw new Error(message); + return retryFailed(message); } tx.db.retryMetric.insert({ id: 0n, @@ -92,23 +95,23 @@ export const init = spacetimedb.init(ctx => { retry.installRetry(ctx); }); -export const retry_fire = spacetimedb.reducer( +export const retryFire = spacetimedb.reducer( { onSchedule: retryTask }, { arg: retryTask.rowType }, retry.reducers.retryFire ); -export const submit_retry_task = spacetimedb.reducer( +export const submitRetryTask = spacetimedb.reducer( retry.reducers.submitRetryTask.params, retry.reducers.submitRetryTask.handler ); -export const add_retry_admin_identity = spacetimedb.reducer( +export const addRetryAdminIdentity = spacetimedb.reducer( retry.reducers.addRetryAdminIdentity.params, retry.reducers.addRetryAdminIdentity.handler ); -export const remove_retry_admin_identity = spacetimedb.reducer( +export const removeRetryAdminIdentity = spacetimedb.reducer( retry.reducers.removeRetryAdminIdentity.params, retry.reducers.removeRetryAdminIdentity.handler ); diff --git a/spacetime-retry-ts/src/handler.ts b/spacetime-retry-ts/src/handler.ts index 0d376bc61f8..1d149ec2ad5 100644 --- a/spacetime-retry-ts/src/handler.ts +++ b/spacetime-retry-ts/src/handler.ts @@ -43,8 +43,10 @@ export function makeRetryDispatch>( ctx: Tx, args: { tag: keyof H & string; value?: unknown } ): RetryResult { - const handler = (handlers as Record)[args.tag]; - if (!handler) throw new Error(`unknown retry handler: ${args.tag}`); + 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); diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index 2be1873e4aa..8f2bf95eca5 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -1,4 +1,9 @@ -import { makeRetryDispatch, type RetryHandler } from './handler'; +import { + makeRetryDispatch, + retryFailed, + type RetryHandler, + type RetryResult, +} from './handler'; import type { Identity, ScheduleAt, Timestamp } from 'spacetimedb'; import type { Infer, VariantsObj } from 'spacetimedb/server'; @@ -7,6 +12,7 @@ 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; @@ -94,7 +100,7 @@ export function createRetrySubmodule( iter(): Iterable; }; retryHistory: { - id: { update(row: RetryHistoryRow): void }; + id: { update(row: RetryHistoryRow): void; delete(id: bigint): boolean }; insert(row: RetryHistoryRow): RetryHistoryRow; iter(): Iterable; }; @@ -160,7 +166,15 @@ export function createRetrySubmodule( function retryHistoryAdmin(ctx: unknown): RetryHistoryRow[] { const retryCtx = retryContext(ctx); - return isAdmin(ctx) ? takeRows(retryCtx.db.retryHistory.iter()) : []; + 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 { @@ -175,13 +189,22 @@ export function createRetrySubmodule( error: undefined, ranAt: retryCtx.timestamp, }); + for (const row of recentHistory(retryCtx).slice(MAX_HISTORY_ROWS)) { + retryCtx.db.retryHistory.id.delete(row.id); + } - const result = dispatchRetry( - retryCtx, - arg.args as RetryDispatchArg & { - tag: keyof H & string; - } - ); + 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({ From 983341cd30245c8c6208c8daec8eafbb0c02d4d0 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Thu, 17 Sep 2026 09:16:40 -0400 Subject: [PATCH 04/32] Use matching workspace artifacts for submodule CI --- .github/workflows/ci.yml | 15 ++++++++++----- spacetime-cron-ts/README.md | 2 +- spacetime-cron-ts/example/README.md | 10 +++------- .../example/src/module_bindings/app/index.ts | 4 ++-- spacetime-rate-limit-ts/example/README.md | 8 +++----- .../example/src/module_bindings/app/index.ts | 4 ++-- 6 files changed, 21 insertions(+), 22 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84107298ad4..96662e736d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1668,10 +1668,12 @@ jobs: # run: spacetime sql quickstart-chat "SELECT * FROM user" typescript-submodules: - needs: [merge_queue_noop] + 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 @@ -1688,11 +1690,14 @@ jobs: - name: Build TypeScript SDK run: pnpm --dir crates/bindings-typescript run build - - name: Install released SpacetimeDB toolchain + - *set-cargo-target-dir + - *download-build-artifacts + - *extract-build-artifacts + + - name: Use the workspace SpacetimeDB toolchain run: | - curl -sSf https://install.spacetimedb.com | sh -s -- --root-dir "$RUNNER_TEMP/spacetime" --yes - echo "$RUNNER_TEMP/spacetime" >> "$GITHUB_PATH" - "$RUNNER_TEMP/spacetime/spacetime" version install 2.8.3 --use --yes + ln -sf spacetimedb-cli "$CARGO_TARGET_DIR/release/spacetime" + echo "$CARGO_TARGET_DIR/release" >> "$GITHUB_PATH" - name: Check submodules run: | diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md index 67b1d72a264..902ea7b0ee0 100644 --- a/spacetime-cron-ts/README.md +++ b/spacetime-cron-ts/README.md @@ -10,7 +10,7 @@ transactions are available. ## Requirements -- SpacetimeDB CLI 2.8.3 or later +- 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 diff --git a/spacetime-cron-ts/example/README.md b/spacetime-cron-ts/example/README.md index 705a53b9298..339e2d3d2fe 100644 --- a/spacetime-cron-ts/example/README.md +++ b/spacetime-cron-ts/example/README.md @@ -24,15 +24,11 @@ This is a local development example. Its scheduling reducers accept any connecte - Node.js 20 or later - pnpm 10 -- SpacetimeDB CLI 2.8.3 with `spacetime:sys@2.0` volatile procedure support +- A SpacetimeDB CLI and server built from this checkout, with the CLI available as `spacetime` - A local SpacetimeDB server -Select the supported CLI release: - -```powershell -spacetime version install 2.8.3 -spacetime version use 2.8.3 -``` +This example uses the workspace SDK. The CLI and server must support the same +host APIs as that SDK. ## Quick start diff --git a/spacetime-cron-ts/example/src/module_bindings/app/index.ts b/spacetime-cron-ts/example/src/module_bindings/app/index.ts index cac97144152..628c885946b 100644 --- a/spacetime-cron-ts/example/src/module_bindings/app/index.ts +++ b/spacetime-cron-ts/example/src/module_bindings/app/index.ts @@ -1,7 +1,7 @@ // 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.8.3 (commit 8e410d2842147bd8e5a32a9589cc00c19f7478e2). +// This was generated using spacetimedb cli version 2.10.1 (commit 5418e2f229c57f503d4306ae9e5fb6df29533f7d). /* eslint-disable */ /* tslint:disable */ @@ -151,7 +151,7 @@ const proceduresSchema = __procedures( /** The remote SpacetimeDB module schema, both runtime and type information. */ const REMOTE_MODULE = { versionInfo: { - cliVersion: "2.8.3" as const, + cliVersion: "2.10.1" as const, }, tables: tablesSchema.schemaType.tables, reducers: reducersSchema.reducersType.reducers, diff --git a/spacetime-rate-limit-ts/example/README.md b/spacetime-rate-limit-ts/example/README.md index 1db70b7ddf7..7f06ad0eb22 100644 --- a/spacetime-rate-limit-ts/example/README.md +++ b/spacetime-rate-limit-ts/example/README.md @@ -17,16 +17,14 @@ under the `rateLimit` namespace. ## Prerequisites - Node.js 20 or later and pnpm 10. -- The released SpacetimeDB 2.8 CLI. +- 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. -Select the supported CLI release, then keep the local server running in a -separate terminal: +This example uses the workspace SDK. Keep the matching local server running in +a separate terminal: ```powershell -spacetime version install 2.8.3 -spacetime version use 2.8.3 spacetime start ``` 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 index e7b95496647..46da420fd5e 100644 --- a/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts @@ -1,7 +1,7 @@ // 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.8.3 (commit 8e410d2842147bd8e5a32a9589cc00c19f7478e2). +// This was generated using spacetimedb cli version 2.10.1 (commit 5418e2f229c57f503d4306ae9e5fb6df29533f7d). /* eslint-disable */ /* tslint:disable */ @@ -170,7 +170,7 @@ const proceduresSchema = __procedures( /** The remote SpacetimeDB module schema, both runtime and type information. */ const REMOTE_MODULE = { versionInfo: { - cliVersion: "2.8.3" as const, + cliVersion: "2.10.1" as const, }, tables: tablesSchema.schemaType.tables, reducers: reducersSchema.reducersType.reducers, From 470045fbce90658819285ce164f70e7d307bb533 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Thu, 24 Sep 2026 13:00:37 -0400 Subject: [PATCH 05/32] Simplify rate-limit policy setup and reject invalid base64 Configure fixed policies once, expose stable errors, keep installers idempotent, and support admin revocation. Remove internal sweep exports and align init naming. Verify packed consumers with the default TypeScript template. --- spacetime-crypto-ts/scripts/test-vectors.ts | 2 + spacetime-crypto-ts/src/index.ts | 8 +- spacetime-crypto-ts/src/timing.ts | 8 +- spacetime-crypto-ts/src/vendors.ts | 4 +- spacetime-rate-limit-ts/README.md | 50 ++++++----- .../example/spacetimedb/src/index.ts | 74 +++++++---------- .../example/src/module_bindings/app/index.ts | 3 + .../remove_rate_limit_admin_reducer.ts | 15 ++++ .../module_bindings/app/rateLimit/types.ts | 2 +- spacetime-rate-limit-ts/package.json | 4 - spacetime-rate-limit-ts/scripts/test.ts | 48 +++++++++++ .../spacetimedb/src/index.ts | 5 +- spacetime-rate-limit-ts/src/index.ts | 11 +-- spacetime-rate-limit-ts/src/limit.ts | 82 +++++++++++++++---- spacetime-rate-limit-ts/src/submodule.ts | 17 ++-- .../src/submodule/install.ts | 10 ++- .../src/submodule/operations.ts | 43 ++++++---- .../src/submodule/schema.ts | 2 +- spacetime-retry-ts/README.md | 4 +- spacetime-retry-ts/spacetimedb/src/index.ts | 2 +- spacetime-retry-ts/src/submodule.ts | 4 +- 21 files changed, 257 insertions(+), 141 deletions(-) create mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/remove_rate_limit_admin_reducer.ts diff --git a/spacetime-crypto-ts/scripts/test-vectors.ts b/spacetime-crypto-ts/scripts/test-vectors.ts index 4d38209cd96..d298d69e398 100644 --- a/spacetime-crypto-ts/scripts/test-vectors.ts +++ b/spacetime-crypto-ts/scripts/test-vectors.ts @@ -194,6 +194,8 @@ for (const malformed of [ 'Zh==', 'Zm9=', 'Zg==\n', + '\u0100AAA', + 'AA\u0100A', ]) { let threw = false; try { diff --git a/spacetime-crypto-ts/src/index.ts b/spacetime-crypto-ts/src/index.ts index bbd42c96545..edc58185181 100644 --- a/spacetime-crypto-ts/src/index.ts +++ b/spacetime-crypto-ts/src/index.ts @@ -1,11 +1,11 @@ -export { sha256, SHA256_BYTES } from './sha256.ts'; -export { hmacSha256 } from './hmac.ts'; +export { sha256, SHA256_BYTES } from './sha256'; +export { hmacSha256 } from './hmac'; export { timingSafeEqual, hexToBytes, bytesToHex, base64ToBytes, -} from './timing.ts'; +} from './timing'; export { verifyStripeSignature, @@ -14,4 +14,4 @@ export { type StripeVerifyOpts, type SvixVerifyOpts, type GithubVerifyOpts, -} from './vendors.ts'; +} from './vendors'; diff --git a/spacetime-crypto-ts/src/timing.ts b/spacetime-crypto-ts/src/timing.ts index bbc530fa7fd..8fa79ebfe24 100644 --- a/spacetime-crypto-ts/src/timing.ts +++ b/spacetime-crypto-ts/src/timing.ts @@ -54,10 +54,10 @@ export function base64ToBytes(b64: string): Uint8Array { 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)]; + const c0 = lookup[s.charCodeAt(i)] ?? -1; + const c1 = lookup[s.charCodeAt(i + 1)] ?? -1; + const c2 = lookup[s.charCodeAt(i + 2)] ?? -1; + const c3 = lookup[s.charCodeAt(i + 3)] ?? -1; if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0) { throw new Error('base64: invalid char'); } diff --git a/spacetime-crypto-ts/src/vendors.ts b/spacetime-crypto-ts/src/vendors.ts index f1299f88fbe..791e16e7b9b 100644 --- a/spacetime-crypto-ts/src/vendors.ts +++ b/spacetime-crypto-ts/src/vendors.ts @@ -3,8 +3,8 @@ // 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'; +import { hmacSha256 } from './hmac'; +import { timingSafeEqual, hexToBytes, base64ToBytes } from './timing'; const enc = new TextEncoder(); diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index 17bbd500788..c88d2c8c781 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -47,7 +47,7 @@ const spacetimedb = schema({ }); export const init = spacetimedb.init(ctx => { - rateLimit.installRateLimit(ctx.as.rateLimit); + rateLimit.install(ctx.as.rateLimit); }); export default spacetimedb; @@ -58,19 +58,19 @@ transaction as the protected write. Derive the actor key from trusted request or session state: ```ts -export const create_post = spacetimedb.procedure( +const postLimiter = rateLimit.client({ + scope: 'post.create', + limit: 10, + windowSeconds: 60, +}); + +export const createPost = 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, - }); + const result = postLimiter.consume(tx.as.rateLimit, { key: actor }); if (!result.allowed) throw new SenderError('rate_limit.blocked'); const body = args.body.trim(); if (!body) throw new SenderError('post.empty'); @@ -104,19 +104,28 @@ 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: +Configure a policy once with `client({ scope, limit, windowSeconds })`. Call +`limiter.consume(ctx, { key, cost?, limit?, windowSeconds? })` in the caller's +transaction. `key` identifies the actor; the library combines it with the scope. +Override limits or windows only for application-owned dynamic policies. + +`install(ctx, { sweepBatch?, sweepIntervalSeconds? })` seeds the publishing +identity and cleanup timer from the host's `init` reducer. Repeated installation +does not add administrators or timers. Admins can grant and revoke access with +`addRateLimitAdmin` and `removeRateLimitAdmin`. + +`errors` exports stable error codes for callers that distinguish failures. + +The root package also exports lower-level helpers for standalone integrations: - `consumeRateLimit` - `buildRateLimitKey` - `installRateLimitState` -- `runRateLimitSweep` - `sweepRateLimits` -- `resolveRateLimitSweepBatch` -The submodule `consume`, `runSweep`, and `reset_buckets` operations are admin-only. +The submodule `consume`, `runSweep`, and `resetBuckets` 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 +the configured limiter shown above. `resetBuckets({ maxRows })` removes 1,000 rows by default and accepts a maximum of 10,000 per call, so destructive maintenance remains bounded. @@ -127,18 +136,19 @@ 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 +## Cleanup defaults + +- 500 expired rows per sweep; at most 10,000. +- One sweep every 30 seconds. -- `DEFAULT_SWEEP_BATCH = 500` -- `MAX_SWEEP_BATCH = 10_000` -- `DEFAULT_SWEEP_INTERVAL_SECONDS = 30n` +Use `buildRateLimitKey(scope, actorKey)` only when reading an existing bucket for +a status view. Consuming a configured policy does not require constructing keys. ## Testing diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts index 5817b1b1baa..333a5dc2edc 100644 --- a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts @@ -34,6 +34,27 @@ const UPGRADE_LIMIT = 2; const REPAIR_LIMIT = 1; const REPAIR_WINDOW_SECONDS = 18; +const tapLimiter = rateLimit.client({ + scope: TAP_SCOPE, + limit: TAP_LIMIT, + windowSeconds: TAP_WINDOW_SECONDS, +}); +const overchargeLimiter = rateLimit.client({ + scope: OVERCHARGE_SCOPE, + limit: OVERCHARGE_LIMIT, + windowSeconds: OVERCHARGE_WINDOW_SECONDS, +}); +const upgradeLimiter = rateLimit.client({ + scope: UPGRADE_SCOPE, + limit: UPGRADE_LIMIT, + windowSeconds: upgradeWindowForState(null), +}); +const repairLimiter = rateLimit.client({ + scope: REPAIR_SCOPE, + limit: REPAIR_LIMIT, + windowSeconds: REPAIR_WINDOW_SECONDS, +}); + const DEFAULT_RETAIN_EVENTS = 2000; const DEFAULT_EVENT_PRUNE_BATCH = 500; const DEFAULT_RETAIN_REACTOR_EVENTS = 80; @@ -382,23 +403,6 @@ function recordReactorEvent( 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 { @@ -413,7 +417,7 @@ function emptyActionResult(tx: Tx, action: string, message: string) { } export const init = spacetimedb.init(ctx => { - rateLimit.installRateLimit(ctx.as.rateLimit); + rateLimit.install(ctx.as.rateLimit); if (ctx.db.rateLimitDemoConfig.singleton.find(true) == null) { ctx.db.rateLimitDemoConfig.insert({ singleton: true, @@ -570,13 +574,10 @@ export const tapReactor = spacetimedb.procedure( let out: ReturnType | null = null; ctx.withTx(tx => { const tapLimit = tapLimitForState(currentState(tx)); - const result = consumeAction( - tx, - TAP_SCOPE, + const result = tapLimiter.consume(tx.as.rateLimit, { key, - tapLimit, - TAP_WINDOW_SECONDS - ); + limit: tapLimit, + }); recordLimitHit(tx, { ...result, limit: tapLimit, @@ -713,13 +714,7 @@ export const overcharge = spacetimedb.procedure( const key = actorKey(ctx); let out: ReturnType | null = null; ctx.withTx(tx => { - const result = consumeAction( - tx, - OVERCHARGE_SCOPE, - key, - OVERCHARGE_LIMIT, - OVERCHARGE_WINDOW_SECONDS - ); + const result = overchargeLimiter.consume(tx.as.rateLimit, { key }); recordLimitHit(tx, { ...result, windowSeconds: OVERCHARGE_WINDOW_SECONDS, @@ -810,13 +805,10 @@ export const buyUpgrade = spacetimedb.procedure( const upgradeWindowSeconds = upgradeWindowForState( tx.db.reactorRoomState.singleton.find(true) ); - const result = consumeAction( - tx, - UPGRADE_SCOPE, + const result = upgradeLimiter.consume(tx.as.rateLimit, { key, - UPGRADE_LIMIT, - upgradeWindowSeconds - ); + windowSeconds: upgradeWindowSeconds, + }); recordLimitHit(tx, { ...result, windowSeconds: upgradeWindowSeconds, @@ -969,13 +961,7 @@ export const repairReactor = spacetimedb.procedure( const key = actorKey(ctx); let out: ReturnType | null = null; ctx.withTx(tx => { - const result = consumeAction( - tx, - REPAIR_SCOPE, - key, - REPAIR_LIMIT, - REPAIR_WINDOW_SECONDS - ); + const result = repairLimiter.consume(tx.as.rateLimit, { key }); recordLimitHit(tx, { ...result, windowSeconds: REPAIR_WINDOW_SECONDS, 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 index 46da420fd5e..ae22c4b9d58 100644 --- a/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts @@ -61,6 +61,7 @@ import RateLimit_AdminRateLimitBucketsRow from "./rateLimit/admin_rate_limit_buc // Import namespace reducer arg schemas import RateLimit_AddRateLimitAdminReducer from "./rateLimit/add_rate_limit_admin_reducer"; +import RateLimit_RemoveRateLimitAdminReducer from "./rateLimit/remove_rate_limit_admin_reducer"; import RateLimit_ResetBucketsReducer from "./rateLimit/reset_buckets_reducer"; import RateLimit_UpdateConfigReducer from "./rateLimit/update_config_reducer"; @@ -151,6 +152,7 @@ const reducersSchema = __reducers( __reducerSchema("set_player_color", SetPlayerColorReducer), __reducerSchema("update_config", UpdateConfigReducer), __reducerSchema("rateLimit.add_rate_limit_admin", RateLimit_AddRateLimitAdminReducer), + __reducerSchema("rateLimit.remove_rate_limit_admin", RateLimit_RemoveRateLimitAdminReducer), __reducerSchema("rateLimit.reset_buckets", RateLimit_ResetBucketsReducer), __reducerSchema("rateLimit.update_config", RateLimit_UpdateConfigReducer), ); @@ -205,6 +207,7 @@ export const reducers = { updateConfig: __reducerAccessors.updateConfig, rateLimit: { addRateLimitAdmin: __reducerAccessors["rateLimit.addRateLimitAdmin"], + removeRateLimitAdmin: __reducerAccessors["rateLimit.removeRateLimitAdmin"], resetBuckets: __reducerAccessors["rateLimit.resetBuckets"], updateConfig: __reducerAccessors["rateLimit.updateConfig"], }, diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/remove_rate_limit_admin_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/remove_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/remove_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/types.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts index 151a90e827f..dc6aa78cab2 100644 --- 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 @@ -15,7 +15,7 @@ export type AdminRateLimitBuckets = __Infer; export const RateLimitAdminIdentity = __t.object("RateLimitAdminIdentity", { identity: __t.identity(), - addedAtMicros: __t.i64(), + addedAt: __t.timestamp(), }); export type RateLimitAdminIdentity = __Infer; diff --git a/spacetime-rate-limit-ts/package.json b/spacetime-rate-limit-ts/package.json index 103fdd58762..b99aa7aa62a 100644 --- a/spacetime-rate-limit-ts/package.json +++ b/spacetime-rate-limit-ts/package.json @@ -11,10 +11,6 @@ "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" diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts index 7f2df80b2d9..fe365e7172e 100644 --- a/spacetime-rate-limit-ts/scripts/test.ts +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -1,6 +1,7 @@ import { Timestamp } from 'spacetimedb'; import { consumeRateLimit, + client, DEFAULT_SWEEP_BATCH, MAX_SWEEP_BATCH, resolveRateLimitSweepBatch, @@ -94,6 +95,53 @@ function makeTx(nowMicros = 0n) { process.stdout.write('\nrate limiter\n'); +{ + const tx = makeTx(); + const tap = client({ scope: 'tap', windowSeconds: 60, limit: 1 }); + const other = client({ scope: 'other', windowSeconds: 60, limit: 1 }); + assert( + tap.consume(tx, { key: 'alice' }).allowed, + 'configured policy allows first call' + ); + assert( + !tap.consume(tx, { key: 'alice' }).allowed, + 'configured policy enforces limit' + ); + assert( + other.consume(tx, { key: 'alice' }).allowed, + 'scopes have independent buckets' + ); + assert( + tap.consume(tx, { key: 'bob' }).allowed, + 'actors have independent buckets' + ); + assert( + tap.consume(tx, { key: 'alice', limit: 2 }).allowed, + 'dynamic limit is supported' + ); +} + +{ + const tx = makeTx(); + consumeRateLimit(tx, { + key: 'fresh', + scope: 's', + limit: 1, + windowSeconds: 100, + }); + consumeRateLimit(tx, { + key: 'expired', + scope: 's', + limit: 1, + windowSeconds: 1, + }); + tx.timestamp = new Timestamp(2_000_000n); + assert( + sweepRateLimits(tx, tx.rows.values()) === 1, + 'sweep accepts unordered rows' + ); +} + { const tx = makeTx(); assertThrows( diff --git a/spacetime-rate-limit-ts/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/spacetimedb/src/index.ts index c057c30f4a0..a0cdf415dac 100644 --- a/spacetime-rate-limit-ts/spacetimedb/src/index.ts +++ b/spacetime-rate-limit-ts/spacetimedb/src/index.ts @@ -1,8 +1,9 @@ import spacetimedb from '../../src/submodule/schema'; -import { installRateLimit } from '../../src/submodule/install'; +import { install } from '../../src/submodule/install'; export { adminRateLimitBuckets, addRateLimitAdmin, + removeRateLimitAdmin, consume, rateLimitSweep, resetBuckets, @@ -13,5 +14,5 @@ export { export default spacetimedb; export const init = spacetimedb.init(ctx => { - installRateLimit(ctx); + install(ctx); }); diff --git a/spacetime-rate-limit-ts/src/index.ts b/spacetime-rate-limit-ts/src/index.ts index 8b6eef65d6c..50569d74676 100644 --- a/spacetime-rate-limit-ts/src/index.ts +++ b/spacetime-rate-limit-ts/src/index.ts @@ -1,17 +1,14 @@ export { - DEFAULT_SWEEP_BATCH, - MAX_SWEEP_BATCH, - assertRateLimitSweepBatch, - DEFAULT_SWEEP_INTERVAL_SECONDS, + client, + errors, consumeRateLimit, installRateLimitState, - resolveRateLimitSweepBatch, - runRateLimitSweep, sweepRateLimits, type ConsumeRateLimitOpts, + type RateLimitPolicy, + type RateLimitInstallOpts, type RateLimitInitCtxLike, type RateLimitResult, - type RateLimitSweepCtxLike, type RateLimitTxLike, } from './limit'; export { buildRateLimitKey } from './key'; diff --git a/spacetime-rate-limit-ts/src/limit.ts b/spacetime-rate-limit-ts/src/limit.ts index c3d5a1ec9ef..9806aa57c67 100644 --- a/spacetime-rate-limit-ts/src/limit.ts +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -1,11 +1,59 @@ import { ScheduleAt, Timestamp } from 'spacetimedb'; +import { buildRateLimitKey } from './key'; 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; +const DEFAULT_SWEEP_INTERVAL_SECONDS = 30n; + +export const errors = { + notAuthorized: 'rate_limit.not_authorized', + invalidScope: 'rate_limit.invalid_scope', + invalidActorKey: 'rate_limit.invalid_actor_key', + invalidLimit: 'rate_limit.invalid_limit', + invalidWindow: 'rate_limit.invalid_window', + invalidCost: 'rate_limit.invalid_cost', + invalidSweepBatch: 'rate_limit.invalid_sweep_batch', + invalidSweepInterval: 'rate_limit.invalid_sweep_interval_seconds', + configMissing: 'rate_limit.config_missing', +} as const; + +export interface RateLimitPolicy { + scope: string; + limit: number; + windowSeconds: number; +} + +/** Configure one policy. Calls may override limits for application-owned dynamic policy. */ +export function client({ scope, limit, windowSeconds }: RateLimitPolicy) { + if (scope.length === 0 || scope.length > 128) + throw new Error(errors.invalidScope); + assertPositiveInt(errors.invalidLimit, limit); + assertPositiveInt(errors.invalidWindow, windowSeconds); + return { + consume( + tx: RateLimitTxLike, + opts: { + key: string; + limit?: number; + windowSeconds?: number; + cost?: number; + } + ): RateLimitResult { + if (opts.key.length === 0 || opts.key.length > 256) + throw new Error(errors.invalidActorKey); + return consumeRateLimit(tx, { + key: buildRateLimitKey(scope, opts.key), + scope, + limit: opts.limit ?? limit, + windowSeconds: opts.windowSeconds ?? windowSeconds, + cost: opts.cost, + }); + }, + }; +} export interface ConsumeRateLimitOpts { key: string; @@ -37,16 +85,16 @@ export type RateLimitResult = retryAfterSeconds: number; }; -function assertPositiveInt(name: string, value: number): void { +function assertPositiveInt(code: string, value: number): void { if (!Number.isInteger(value) || value <= 0 || value > U32_MAX) { - throw new Error(`rate_limit.invalid_${name}`); + throw new Error(code); } } export function assertRateLimitSweepBatch(value: number): void { - assertPositiveInt('sweep_batch', value); + assertPositiveInt(errors.invalidSweepBatch, value); if (value > MAX_SWEEP_BATCH) { - throw new Error('rate_limit.invalid_sweep_batch'); + throw new Error(errors.invalidSweepBatch); } } @@ -130,17 +178,15 @@ export function installRateLimitState( assertRateLimitSweepBatch(sweepBatch); const sweepIntervalSeconds = opts?.sweepIntervalSeconds ?? DEFAULT_SWEEP_INTERVAL_SECONDS; - if (sweepIntervalSeconds <= 0n) - throw new Error('rate_limit.invalid_sweep_interval_seconds'); + if (sweepIntervalSeconds <= 0n) throw new Error(errors.invalidSweepInterval); const existing = ctx.db.rateLimitConfig.singleton.find(true); - if (!existing) { - ctx.db.rateLimitConfig.insert({ - singleton: true, - sweepBatch, - updatedAt: ctx.timestamp, - }); - } + if (existing) return; + ctx.db.rateLimitConfig.insert({ + singleton: true, + sweepBatch, + updatedAt: ctx.timestamp, + }); ctx.db.rateLimitSweepTick.insert({ scheduledId: 0n, @@ -187,10 +233,10 @@ export function consumeRateLimit( tx: RateLimitTxLike, opts: ConsumeRateLimitOpts ): RateLimitResult { - assertPositiveInt('limit', opts.limit); - assertPositiveInt('window', opts.windowSeconds); + assertPositiveInt(errors.invalidLimit, opts.limit); + assertPositiveInt(errors.invalidWindow, opts.windowSeconds); const cost = opts.cost ?? 1; - assertPositiveInt('cost', cost); + assertPositiveInt(errors.invalidCost, cost); const now = tx.timestamp as Timestamp; const resetAt = plusSeconds(now, opts.windowSeconds); @@ -289,7 +335,7 @@ export function sweepRateLimits( let deleted = 0; for (const row of expiredRows) { if (deleted >= maxRows) break; - if ((row.expiresAt.microsSinceUnixEpoch as bigint) > nowMicros) break; + if ((row.expiresAt.microsSinceUnixEpoch as bigint) > nowMicros) continue; tx.db.rateLimitBucket.delete(row); deleted++; } diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts index ed5e49da5c2..1792378916b 100644 --- a/spacetime-rate-limit-ts/src/submodule.ts +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -1,25 +1,20 @@ export { default } from './submodule/schema'; -export { installRateLimit } from './submodule/install'; +export { install } from './submodule/install'; export { - DEFAULT_SWEEP_BATCH, - MAX_SWEEP_BATCH, - assertRateLimitSweepBatch, - DEFAULT_SWEEP_INTERVAL_SECONDS, + client, + errors, consumeRateLimit, - installRateLimitState, - resolveRateLimitSweepBatch, - runRateLimitSweep, - sweepRateLimits, type ConsumeRateLimitOpts, - type RateLimitInitCtxLike, + type RateLimitPolicy, + type RateLimitInstallOpts, type RateLimitResult, - type RateLimitSweepCtxLike, type RateLimitTxLike, } from './limit'; export { buildRateLimitKey } from './key'; export { adminRateLimitBuckets, addRateLimitAdmin, + removeRateLimitAdmin, consume, rateLimitSweep, resetBuckets, diff --git a/spacetime-rate-limit-ts/src/submodule/install.ts b/spacetime-rate-limit-ts/src/submodule/install.ts index 0ad4b1ffcb3..060f56092e0 100644 --- a/spacetime-rate-limit-ts/src/submodule/install.ts +++ b/spacetime-rate-limit-ts/src/submodule/install.ts @@ -1,12 +1,14 @@ -import { DEFAULT_SWEEP_BATCH, installRateLimitState } from '../index'; +import { installRateLimitState, type RateLimitInstallOpts } from '../limit'; import type { ReducerModuleCtx } from './schema'; -export function installRateLimit(ctx: ReducerModuleCtx) { +/** Call from the host's init reducer to seed its publishing identity and cleanup timer. */ +export function install(ctx: ReducerModuleCtx, opts?: RateLimitInstallOpts) { + if (ctx.db.rateLimitConfig.singleton.find(true)) return; if (ctx.db.rateLimitAdminIdentity.identity.find(ctx.sender) == null) { ctx.db.rateLimitAdminIdentity.insert({ identity: ctx.sender, - addedAtMicros: ctx.timestamp.microsSinceUnixEpoch, + addedAt: ctx.timestamp, }); } - installRateLimitState(ctx, { sweepBatch: DEFAULT_SWEEP_BATCH }); + installRateLimitState(ctx, opts); } diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts index 6a3c3d88d5b..57e50234ae3 100644 --- a/spacetime-rate-limit-ts/src/submodule/operations.ts +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -5,7 +5,8 @@ import { MAX_SWEEP_BATCH, runRateLimitSweep, sweepRateLimits, -} from '../index'; + errors, +} from '../limit'; import { rateLimitBucket, rateLimitSweepTick, @@ -36,13 +37,13 @@ function isAdmin(ctx: ViewModuleCtx): boolean { function requireAdmin(ctx: ReducerModuleCtx): void { if (ctx.db.rateLimitAdminIdentity.identity.find(ctx.sender) == null) { - throw new SenderError('rate_limit.not_authorized'); + throw new SenderError(errors.notAuthorized); } } -function toU32(name: string, value: number, max = 0xffff_ffff): number { +function toU32(code: string, value: number, max = 0xffff_ffff): number { if (!Number.isInteger(value) || value <= 0 || value > max) { - throw new SenderError(`rate_limit.invalid_${name}`); + throw new SenderError(code); } return value; } @@ -64,14 +65,17 @@ export const consume = spacetimedb.procedure( 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'); + throw new SenderError(errors.invalidScope); } if (actorKey.length === 0 || actorKey.length > MAX_ACTOR_KEY_LENGTH) { - throw new SenderError('rate_limit.invalid_actor_key'); + throw new SenderError(errors.invalidActorKey); } - const limit = toU32('limit', Number(args.limit)); - const windowSeconds = toU32('window_seconds', Number(args.windowSeconds)); - const cost = toU32('cost', Number(args.cost ?? 1)); + const limit = toU32(errors.invalidLimit, Number(args.limit)); + const windowSeconds = toU32( + errors.invalidWindow, + Number(args.windowSeconds) + ); + const cost = toU32(errors.invalidCost, Number(args.cost ?? 1)); const key = buildRateLimitKey(scope, actorKey); const out = ctx.withTx(tx => { @@ -94,7 +98,6 @@ export const consume = spacetimedb.procedure( resetAt: r.resetAt, }; }); - if (!out) throw new Error('rate_limit.consume_tx_failed'); return out; } ); @@ -106,7 +109,11 @@ export const runSweep = spacetimedb.procedure( const maxRows = args.maxRows === undefined ? undefined - : toU32('sweep_batch', Number(args.maxRows), MAX_SWEEP_BATCH); + : toU32( + errors.invalidSweepBatch, + Number(args.maxRows), + MAX_SWEEP_BATCH + ); return ctx.withTx(tx => { requireAdmin(tx); return sweepRateLimits( @@ -127,22 +134,30 @@ export const addRateLimitAdmin = spacetimedb.reducer( if (ctx.db.rateLimitAdminIdentity.identity.find(args.identity) == null) { ctx.db.rateLimitAdminIdentity.insert({ identity: args.identity, - addedAtMicros: ctx.timestamp.microsSinceUnixEpoch, + addedAt: ctx.timestamp, }); } } ); +export const removeRateLimitAdmin = spacetimedb.reducer( + { identity: t.identity() }, + (ctx, { identity }) => { + requireAdmin(ctx); + ctx.db.rateLimitAdminIdentity.identity.delete(identity); + } +); + 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'); + if (!cfg) throw new Error(errors.configMissing); ctx.db.rateLimitConfig.singleton.update({ ...cfg, sweepBatch: toU32( - 'sweep_batch', + errors.invalidSweepBatch, Number(args.sweepBatch), MAX_SWEEP_BATCH ), diff --git a/spacetime-rate-limit-ts/src/submodule/schema.ts b/spacetime-rate-limit-ts/src/submodule/schema.ts index 3d546331a75..ec4be8b76b1 100644 --- a/spacetime-rate-limit-ts/src/submodule/schema.ts +++ b/spacetime-rate-limit-ts/src/submodule/schema.ts @@ -25,7 +25,7 @@ export const rateLimitAdminIdentity = table( { name: 'rate_limit_admin_identity', public: false }, { identity: t.identity().primaryKey(), - addedAtMicros: t.i64(), + addedAt: t.timestamp(), } ); diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md index d14685c1f5e..5fa47884ebd 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -65,7 +65,7 @@ export const submitRetryTask = db.reducer( retry.reducers.submitRetryTask.handler ); -export const init = db.init(ctx => retry.installRetry(ctx)); +export const init = db.init(ctx => retry.install(ctx)); export default db; ``` @@ -88,7 +88,7 @@ view returns these attempts newest first. - `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. +- `install(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 diff --git a/spacetime-retry-ts/spacetimedb/src/index.ts b/spacetime-retry-ts/spacetimedb/src/index.ts index 2bb9da37e94..5c1b16dbf72 100644 --- a/spacetime-retry-ts/spacetimedb/src/index.ts +++ b/spacetime-retry-ts/spacetimedb/src/index.ts @@ -92,7 +92,7 @@ export const retryHistoryAdmin = spacetimedb.view( ); export const init = spacetimedb.init(ctx => { - retry.installRetry(ctx); + retry.install(ctx); }); export const retryFire = spacetimedb.reducer( diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index 8f2bf95eca5..7934723687d 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -121,7 +121,7 @@ export function createRetrySubmodule( const dispatchRetry = makeRetryDispatch(handlers); - function installRetry(ctx: unknown): void { + function install(ctx: unknown): void { const retryCtx = retryContext(ctx); if (retryCtx.db.retryAdminIdentity.identity.find(retryCtx.sender) == null) { retryCtx.db.retryAdminIdentity.insert({ @@ -327,7 +327,7 @@ export function createRetrySubmodule( retryArgs, retryHistoryStatus, RetryHistoryStatus, - installRetry, + install, requireAdmin, views: { retryTasksAdmin, From 0cce532420fd698a3a099d86ec02c275bec236f4 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Thu, 24 Sep 2026 13:33:24 -0400 Subject: [PATCH 06/32] Keep Retry compatible with generated consumer TypeScript options --- spacetime-retry-ts/src/handler.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spacetime-retry-ts/src/handler.ts b/spacetime-retry-ts/src/handler.ts index 1d149ec2ad5..64743407137 100644 --- a/spacetime-retry-ts/src/handler.ts +++ b/spacetime-retry-ts/src/handler.ts @@ -43,7 +43,7 @@ export function makeRetryDispatch>( ctx: Tx, args: { tag: keyof H & string; value?: unknown } ): RetryResult { - if (!Object.hasOwn(handlers, args.tag)) { + if (!Object.prototype.hasOwnProperty.call(handlers, args.tag)) { throw new Error(`unknown retry handler: ${args.tag}`); } const handler = handlers[args.tag]; From 8ad05ee70b3aff6b4ea1f0c34121c89d1b57d7f4 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 10:03:37 -0400 Subject: [PATCH 07/32] Use shared licenses and preserve Apache text in core packages --- spacetime-cron-ts/LICENSE.txt | 202 +-------------------------- spacetime-cron-ts/package.json | 6 +- spacetime-crypto-ts/LICENSE.txt | 202 +-------------------------- spacetime-crypto-ts/package.json | 6 +- spacetime-rate-limit-ts/LICENSE.txt | 202 +-------------------------- spacetime-rate-limit-ts/package.json | 6 +- spacetime-retry-ts/LICENSE.txt | 202 +-------------------------- spacetime-retry-ts/package.json | 6 +- 8 files changed, 20 insertions(+), 812 deletions(-) mode change 100644 => 120000 spacetime-cron-ts/LICENSE.txt mode change 100644 => 120000 spacetime-crypto-ts/LICENSE.txt mode change 100644 => 120000 spacetime-rate-limit-ts/LICENSE.txt mode change 100644 => 120000 spacetime-retry-ts/LICENSE.txt diff --git a/spacetime-cron-ts/LICENSE.txt b/spacetime-cron-ts/LICENSE.txt deleted file mode 100644 index 4e61a2122e7..00000000000 --- a/spacetime-cron-ts/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - 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/LICENSE.txt b/spacetime-cron-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-cron-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-cron-ts/package.json b/spacetime-cron-ts/package.json index 808da1f0c00..68acfcd02b6 100644 --- a/spacetime-cron-ts/package.json +++ b/spacetime-cron-ts/package.json @@ -18,7 +18,7 @@ }, "files": [ "src", - "LICENSE.txt", + "LICENSE", "README.md" ], "publishConfig": { @@ -50,7 +50,9 @@ "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" + "test:validation": "tsx scripts/test-validation.ts", + "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "dependencies": { "cron-parser": "5.5.0" diff --git a/spacetime-crypto-ts/LICENSE.txt b/spacetime-crypto-ts/LICENSE.txt deleted file mode 100644 index 4e61a2122e7..00000000000 --- a/spacetime-crypto-ts/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - 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/LICENSE.txt b/spacetime-crypto-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-crypto-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-crypto-ts/package.json b/spacetime-crypto-ts/package.json index e6b20c42870..451b4d59878 100644 --- a/spacetime-crypto-ts/package.json +++ b/spacetime-crypto-ts/package.json @@ -18,7 +18,7 @@ }, "files": [ "src", - "LICENSE.txt", + "LICENSE", "README.md" ], "publishConfig": { @@ -44,7 +44,9 @@ "format": "prettier . --write --ignore-path ../.prettierignore", "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", - "test": "tsx scripts/test-vectors.ts" + "test": "tsx scripts/test-vectors.ts", + "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "devDependencies": { "eslint": "^9.17.0", diff --git a/spacetime-rate-limit-ts/LICENSE.txt b/spacetime-rate-limit-ts/LICENSE.txt deleted file mode 100644 index 4e61a2122e7..00000000000 --- a/spacetime-rate-limit-ts/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - 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/LICENSE.txt b/spacetime-rate-limit-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-rate-limit-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-rate-limit-ts/package.json b/spacetime-rate-limit-ts/package.json index b99aa7aa62a..569f42a013b 100644 --- a/spacetime-rate-limit-ts/package.json +++ b/spacetime-rate-limit-ts/package.json @@ -18,7 +18,7 @@ }, "files": [ "src", - "LICENSE.txt", + "LICENSE", "README.md" ], "publishConfig": { @@ -44,7 +44,9 @@ "format": "prettier . --write --ignore-path ../.prettierignore", "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", - "test": "tsx scripts/test.ts" + "test": "tsx scripts/test.ts", + "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "peerDependencies": { "spacetimedb": "workspace:^" diff --git a/spacetime-retry-ts/LICENSE.txt b/spacetime-retry-ts/LICENSE.txt deleted file mode 100644 index 4e61a2122e7..00000000000 --- a/spacetime-retry-ts/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - 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/LICENSE.txt b/spacetime-retry-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-retry-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-retry-ts/package.json b/spacetime-retry-ts/package.json index 2e9b188485b..1335d34fc0e 100644 --- a/spacetime-retry-ts/package.json +++ b/spacetime-retry-ts/package.json @@ -18,7 +18,7 @@ }, "files": [ "src", - "LICENSE.txt", + "LICENSE", "README.md" ], "publishConfig": { @@ -44,7 +44,9 @@ "format": "prettier . --write --ignore-path ../.prettierignore", "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", - "test": "tsx scripts/test.ts" + "test": "tsx scripts/test.ts", + "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "peerDependencies": { "spacetimedb": "workspace:^" From 094df0ed2107fe3a359f5e4ee7a4c344802fc96c Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:05:13 -0400 Subject: [PATCH 08/32] Regenerate lockfile from master to drop unrelated dependency changes --- pnpm-lock.yaml | 872 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 583 insertions(+), 289 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2ad8187bffa..49ca2adc154 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.23.12)(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.21.0)(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.23.12)(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.21.0)(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.23.12)(typescript@5.9.3)(yaml@2.8.2) + version: 8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(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.23.12)(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.21.0)(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.23.12)(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.21.0)(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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) + 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)) typescript: specifier: ^5.2.2 version: 5.9.2 vite: specifier: ^7.1.5 - 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) + 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) docs: dependencies: @@ -360,7 +360,7 @@ importers: version: link:../crates/bindings-typescript tsx: specifier: ^4.21.0 - version: 4.23.12 + version: 4.21.0 typescript: specifier: ^5.9.3 version: 5.9.3 @@ -391,7 +391,7 @@ importers: version: 0.28.2 tsx: specifier: ^4.21.0 - version: 4.23.12 + version: 4.21.0 typescript: specifier: ^5.9.3 version: 5.9.3 @@ -432,7 +432,7 @@ importers: dependencies: '@noble/hashes': specifier: ^2.2.0 - version: 2.3.0 + version: 2.4.0 devDependencies: '@types/node': specifier: ^22.10.2 @@ -445,7 +445,7 @@ importers: version: 3.6.2 tsx: specifier: ^4.21.0 - version: 4.23.12 + version: 4.21.0 typescript: specifier: ^5.9.3 version: 5.9.3 @@ -466,7 +466,7 @@ importers: version: link:../crates/bindings-typescript tsx: specifier: ^4.21.0 - version: 4.23.12 + version: 4.21.0 typescript: specifier: ^5.9.3 version: 5.9.3 @@ -497,7 +497,7 @@ importers: version: 0.28.2 tsx: specifier: ^4.21.0 - version: 4.23.12 + version: 4.21.0 typescript: specifier: ^5.9.3 version: 5.9.3 @@ -550,7 +550,7 @@ importers: version: link:../crates/bindings-typescript tsx: specifier: ^4.21.0 - version: 4.23.12 + version: 4.21.0 typescript: specifier: ^5.9.3 version: 5.9.3 @@ -590,7 +590,7 @@ importers: 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) + 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) templates/angular-ts: dependencies: @@ -618,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@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) + 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) '@angular/cli': specifier: ^21.2.12 - version: 21.2.13(@types/node@25.9.5)(chokidar@5.0.0) + version: 21.2.13(@types/node@24.3.0)(chokidar@5.0.0) '@angular/compiler-cli': specifier: ^21.2.12 version: 21.2.15(@angular/compiler@21.2.15)(typescript@5.9.3) @@ -656,7 +656,7 @@ importers: version: 5.6.3 vite: specifier: ^7.1.5 - 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) + 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) templates/bun-ts: dependencies: @@ -666,7 +666,7 @@ importers: devDependencies: '@types/bun': specifier: latest - version: 1.4.1 + version: 1.4.2 bun: specifier: ^1.3.2 version: 1.3.9 @@ -706,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.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)) eslint: specifier: ^9.17.0 version: 9.33.0(jiti@2.6.1) @@ -733,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + 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) vitest: specifier: 3.2.4 - 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) + 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) templates/chat-react-ts/spacetimedb: dependencies: @@ -771,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.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)) eslint: specifier: ^9.17.0 version: 9.33.0(jiti@2.6.1) @@ -795,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + 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) templates/keynote-2: dependencies: @@ -893,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.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)) typescript: specifier: ~5.6.2 version: 5.6.3 vite: specifier: ^7.1.5 - 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) + 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) templates/money-exchange-react-ts: dependencies: @@ -933,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.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)) eslint: specifier: ^9.17.0 version: 9.33.0(jiti@2.6.1) @@ -960,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + 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) vitest: specifier: 3.2.4 - 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) + 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) templates/nuxt-ts: dependencies: nuxt: specifier: ~3.16.0 - 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) + 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.4.2)(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.2)(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) spacetimedb: specifier: workspace:* version: link:../../crates/bindings-typescript @@ -1001,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.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)) typescript: specifier: ~5.6.2 version: 5.6.3 vite: specifier: ^7.1.5 - 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) + 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) templates/remix-ts: dependencies: @@ -1035,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@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) + 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) '@types/react': specifier: ^18.3.18 version: 18.3.23 @@ -1047,7 +1047,7 @@ importers: version: 5.6.3 vite: specifier: ^5.4.0 - version: 5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) + version: 5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) templates/solid-ts: dependencies: @@ -1063,10 +1063,10 @@ importers: version: 5.6.3 vite: specifier: ^7.1.5 - 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) + 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) 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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(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@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) templates/svelte-ts: dependencies: @@ -1076,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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) + 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)) svelte: specifier: ^5.0.0 version: 5.46.4 @@ -1088,7 +1088,7 @@ importers: version: 5.6.3 vite: specifier: ^6.4.1 - 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) + 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) templates/tanstack-ts: dependencies: @@ -1109,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.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) + 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) react: specifier: ^19.0.0 version: 19.2.4 @@ -1131,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.23.12)(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.21.0)(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.23.12)(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.21.0)(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.23.12)(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.21.0)(yaml@2.8.2)) templates/vue-ts: dependencies: @@ -1153,13 +1153,13 @@ importers: devDependencies: '@vitejs/plugin-vue': specifier: ^5.2.4 - 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)) + 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)) typescript: specifier: ~5.6.2 version: 5.6.3 vite: specifier: ^6.4.1 - 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) + 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) vue-tsc: specifier: ^2.2.0 version: 2.2.12(typescript@5.6.3) @@ -2811,6 +2811,12 @@ packages: cpu: [ppc64] os: [aix] + '@esbuild/aix-ppc64@0.27.2': + resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + '@esbuild/aix-ppc64@0.27.3': resolution: {integrity: sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==} engines: {node: '>=18'} @@ -2853,6 +2859,12 @@ packages: cpu: [arm64] os: [android] + '@esbuild/android-arm64@0.27.2': + resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + '@esbuild/android-arm64@0.27.3': resolution: {integrity: sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==} engines: {node: '>=18'} @@ -2895,6 +2907,12 @@ packages: cpu: [arm] os: [android] + '@esbuild/android-arm@0.27.2': + resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + '@esbuild/android-arm@0.27.3': resolution: {integrity: sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==} engines: {node: '>=18'} @@ -2937,6 +2955,12 @@ packages: cpu: [x64] os: [android] + '@esbuild/android-x64@0.27.2': + resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + '@esbuild/android-x64@0.27.3': resolution: {integrity: sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==} engines: {node: '>=18'} @@ -2979,6 +3003,12 @@ packages: cpu: [arm64] os: [darwin] + '@esbuild/darwin-arm64@0.27.2': + resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + '@esbuild/darwin-arm64@0.27.3': resolution: {integrity: sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==} engines: {node: '>=18'} @@ -3021,6 +3051,12 @@ packages: cpu: [x64] os: [darwin] + '@esbuild/darwin-x64@0.27.2': + resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + '@esbuild/darwin-x64@0.27.3': resolution: {integrity: sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==} engines: {node: '>=18'} @@ -3063,6 +3099,12 @@ packages: cpu: [arm64] os: [freebsd] + '@esbuild/freebsd-arm64@0.27.2': + resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + '@esbuild/freebsd-arm64@0.27.3': resolution: {integrity: sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==} engines: {node: '>=18'} @@ -3105,6 +3147,12 @@ packages: cpu: [x64] os: [freebsd] + '@esbuild/freebsd-x64@0.27.2': + resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + '@esbuild/freebsd-x64@0.27.3': resolution: {integrity: sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==} engines: {node: '>=18'} @@ -3147,6 +3195,12 @@ packages: cpu: [arm64] os: [linux] + '@esbuild/linux-arm64@0.27.2': + resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + '@esbuild/linux-arm64@0.27.3': resolution: {integrity: sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==} engines: {node: '>=18'} @@ -3189,6 +3243,12 @@ packages: cpu: [arm] os: [linux] + '@esbuild/linux-arm@0.27.2': + resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + '@esbuild/linux-arm@0.27.3': resolution: {integrity: sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==} engines: {node: '>=18'} @@ -3231,6 +3291,12 @@ packages: cpu: [ia32] os: [linux] + '@esbuild/linux-ia32@0.27.2': + resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + '@esbuild/linux-ia32@0.27.3': resolution: {integrity: sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==} engines: {node: '>=18'} @@ -3273,6 +3339,12 @@ packages: cpu: [loong64] os: [linux] + '@esbuild/linux-loong64@0.27.2': + resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + '@esbuild/linux-loong64@0.27.3': resolution: {integrity: sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==} engines: {node: '>=18'} @@ -3315,6 +3387,12 @@ packages: cpu: [mips64el] os: [linux] + '@esbuild/linux-mips64el@0.27.2': + resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + '@esbuild/linux-mips64el@0.27.3': resolution: {integrity: sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==} engines: {node: '>=18'} @@ -3357,6 +3435,12 @@ packages: cpu: [ppc64] os: [linux] + '@esbuild/linux-ppc64@0.27.2': + resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + '@esbuild/linux-ppc64@0.27.3': resolution: {integrity: sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==} engines: {node: '>=18'} @@ -3399,6 +3483,12 @@ packages: cpu: [riscv64] os: [linux] + '@esbuild/linux-riscv64@0.27.2': + resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + '@esbuild/linux-riscv64@0.27.3': resolution: {integrity: sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==} engines: {node: '>=18'} @@ -3441,6 +3531,12 @@ packages: cpu: [s390x] os: [linux] + '@esbuild/linux-s390x@0.27.2': + resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + '@esbuild/linux-s390x@0.27.3': resolution: {integrity: sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==} engines: {node: '>=18'} @@ -3483,6 +3579,12 @@ packages: cpu: [x64] os: [linux] + '@esbuild/linux-x64@0.27.2': + resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + '@esbuild/linux-x64@0.27.3': resolution: {integrity: sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==} engines: {node: '>=18'} @@ -3513,6 +3615,12 @@ packages: cpu: [arm64] os: [netbsd] + '@esbuild/netbsd-arm64@0.27.2': + resolution: {integrity: sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + '@esbuild/netbsd-arm64@0.27.3': resolution: {integrity: sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==} engines: {node: '>=18'} @@ -3555,6 +3663,12 @@ packages: cpu: [x64] os: [netbsd] + '@esbuild/netbsd-x64@0.27.2': + resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + '@esbuild/netbsd-x64@0.27.3': resolution: {integrity: sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==} engines: {node: '>=18'} @@ -3585,6 +3699,12 @@ packages: cpu: [arm64] os: [openbsd] + '@esbuild/openbsd-arm64@0.27.2': + resolution: {integrity: sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + '@esbuild/openbsd-arm64@0.27.3': resolution: {integrity: sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==} engines: {node: '>=18'} @@ -3627,6 +3747,12 @@ packages: cpu: [x64] os: [openbsd] + '@esbuild/openbsd-x64@0.27.2': + resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + '@esbuild/openbsd-x64@0.27.3': resolution: {integrity: sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==} engines: {node: '>=18'} @@ -3651,6 +3777,12 @@ packages: cpu: [arm64] os: [openharmony] + '@esbuild/openharmony-arm64@0.27.2': + resolution: {integrity: sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + '@esbuild/openharmony-arm64@0.27.3': resolution: {integrity: sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==} engines: {node: '>=18'} @@ -3693,6 +3825,12 @@ packages: cpu: [x64] os: [sunos] + '@esbuild/sunos-x64@0.27.2': + resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + '@esbuild/sunos-x64@0.27.3': resolution: {integrity: sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==} engines: {node: '>=18'} @@ -3735,6 +3873,12 @@ packages: cpu: [arm64] os: [win32] + '@esbuild/win32-arm64@0.27.2': + resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + '@esbuild/win32-arm64@0.27.3': resolution: {integrity: sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==} engines: {node: '>=18'} @@ -3777,6 +3921,12 @@ packages: cpu: [ia32] os: [win32] + '@esbuild/win32-ia32@0.27.2': + resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + '@esbuild/win32-ia32@0.27.3': resolution: {integrity: sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==} engines: {node: '>=18'} @@ -3819,6 +3969,12 @@ packages: cpu: [x64] os: [win32] + '@esbuild/win32-x64@0.27.2': + resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@esbuild/win32-x64@0.27.3': resolution: {integrity: sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==} engines: {node: '>=18'} @@ -4396,42 +4552,49 @@ 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==} @@ -4467,8 +4630,8 @@ 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==} + '@noble/hashes@2.4.0': + resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==} engines: {node: '>= 20.19.0'} '@node-rs/jieba-android-arm-eabi@1.10.4': @@ -4909,36 +5072,42 @@ 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==} @@ -5947,121 +6116,145 @@ 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==} @@ -6606,8 +6799,8 @@ packages: '@types/bun@1.3.9': resolution: {integrity: sha512-KQ571yULOdWJiMH+RIWIOZ7B2RXQGpL1YQrBtLIV3FqDcCu6FsbFUBwhdKUlCKUpS3PJDsHlJ1QKlpxoVR+xtw==} - '@types/bun@1.4.1': - resolution: {integrity: sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA==} + '@types/bun@1.4.2': + resolution: {integrity: sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ==} '@types/chai@5.2.2': resolution: {integrity: sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==} @@ -6732,8 +6925,8 @@ packages: '@types/node@22.18.0': resolution: {integrity: sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ==} - '@types/node@25.9.5': - resolution: {integrity: sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg==} + '@types/node@24.3.0': + resolution: {integrity: sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==} '@types/object-inspect@1.13.0': resolution: {integrity: sha512-lwGTVESDDV+XsQ1pH4UifpJ1f7OtXzQ6QBOX2Afq2bM/T3oOt8hF6exJMjjIjtEWeAN2YAo25J7HxWh97CCz9w==} @@ -7982,8 +8175,8 @@ packages: bun-types@1.3.9: resolution: {integrity: sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg==} - bun-types@1.4.1: - resolution: {integrity: sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA==} + bun-types@1.4.2: + resolution: {integrity: sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w==} bun@1.3.9: resolution: {integrity: sha512-v5hkh1us7sMNjfimWE70flYbD5I1/qWQaqmJ45q2qk5H/7muQVa478LSVRSFyGTBUBog2LsPQnfIRdjyWJRY+A==} @@ -9149,6 +9342,11 @@ packages: engines: {node: '>=18'} hasBin: true + esbuild@0.27.2: + resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==} + engines: {node: '>=18'} + hasBin: true + esbuild@0.27.3: resolution: {integrity: sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==} engines: {node: '>=18'} @@ -14196,11 +14394,6 @@ 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} @@ -14285,8 +14478,8 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - undici-types@7.24.6: - resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + undici-types@7.10.0: + resolution: {integrity: sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==} undici@6.21.3: resolution: {integrity: sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==} @@ -14629,8 +14822,8 @@ packages: v8-compile-cache-lib@3.0.1: resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==} - valibot@1.4.2: - resolution: {integrity: sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg==} + valibot@1.2.0: + resolution: {integrity: sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg==} peerDependencies: typescript: '>=5' peerDependenciesMeta: @@ -15586,7 +15779,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@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/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)': dependencies: '@ampproject/remapping': 2.3.0 '@angular-devkit/architect': 0.2102.13(chokidar@5.0.0) @@ -15595,8 +15788,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@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)) + '@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)) beasties: 0.4.1 browserslist: 4.28.1 esbuild: 0.27.3 @@ -15617,14 +15810,14 @@ snapshots: tslib: 2.8.1 typescript: 5.9.3 undici: 7.24.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) + 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) 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.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) transitivePeerDependencies: - '@types/node' - chokidar @@ -15638,13 +15831,13 @@ snapshots: - tsx - yaml - '@angular/cli@21.2.13(@types/node@25.9.5)(chokidar@5.0.0)': + '@angular/cli@21.2.13(@types/node@24.3.0)(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@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) + '@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) '@modelcontextprotocol/sdk': 1.26.0(zod@4.3.6) '@schematics/angular': 21.2.13(chokidar@5.0.0) '@yarnpkg/lockfile': 1.1.0 @@ -18174,6 +18367,9 @@ snapshots: '@esbuild/aix-ppc64@0.27.0': optional: true + '@esbuild/aix-ppc64@0.27.2': + optional: true + '@esbuild/aix-ppc64@0.27.3': optional: true @@ -18195,6 +18391,9 @@ snapshots: '@esbuild/android-arm64@0.27.0': optional: true + '@esbuild/android-arm64@0.27.2': + optional: true + '@esbuild/android-arm64@0.27.3': optional: true @@ -18216,6 +18415,9 @@ snapshots: '@esbuild/android-arm@0.27.0': optional: true + '@esbuild/android-arm@0.27.2': + optional: true + '@esbuild/android-arm@0.27.3': optional: true @@ -18237,6 +18439,9 @@ snapshots: '@esbuild/android-x64@0.27.0': optional: true + '@esbuild/android-x64@0.27.2': + optional: true + '@esbuild/android-x64@0.27.3': optional: true @@ -18258,6 +18463,9 @@ snapshots: '@esbuild/darwin-arm64@0.27.0': optional: true + '@esbuild/darwin-arm64@0.27.2': + optional: true + '@esbuild/darwin-arm64@0.27.3': optional: true @@ -18279,6 +18487,9 @@ snapshots: '@esbuild/darwin-x64@0.27.0': optional: true + '@esbuild/darwin-x64@0.27.2': + optional: true + '@esbuild/darwin-x64@0.27.3': optional: true @@ -18300,6 +18511,9 @@ snapshots: '@esbuild/freebsd-arm64@0.27.0': optional: true + '@esbuild/freebsd-arm64@0.27.2': + optional: true + '@esbuild/freebsd-arm64@0.27.3': optional: true @@ -18321,6 +18535,9 @@ snapshots: '@esbuild/freebsd-x64@0.27.0': optional: true + '@esbuild/freebsd-x64@0.27.2': + optional: true + '@esbuild/freebsd-x64@0.27.3': optional: true @@ -18342,6 +18559,9 @@ snapshots: '@esbuild/linux-arm64@0.27.0': optional: true + '@esbuild/linux-arm64@0.27.2': + optional: true + '@esbuild/linux-arm64@0.27.3': optional: true @@ -18363,6 +18583,9 @@ snapshots: '@esbuild/linux-arm@0.27.0': optional: true + '@esbuild/linux-arm@0.27.2': + optional: true + '@esbuild/linux-arm@0.27.3': optional: true @@ -18384,6 +18607,9 @@ snapshots: '@esbuild/linux-ia32@0.27.0': optional: true + '@esbuild/linux-ia32@0.27.2': + optional: true + '@esbuild/linux-ia32@0.27.3': optional: true @@ -18405,6 +18631,9 @@ snapshots: '@esbuild/linux-loong64@0.27.0': optional: true + '@esbuild/linux-loong64@0.27.2': + optional: true + '@esbuild/linux-loong64@0.27.3': optional: true @@ -18426,6 +18655,9 @@ snapshots: '@esbuild/linux-mips64el@0.27.0': optional: true + '@esbuild/linux-mips64el@0.27.2': + optional: true + '@esbuild/linux-mips64el@0.27.3': optional: true @@ -18447,6 +18679,9 @@ snapshots: '@esbuild/linux-ppc64@0.27.0': optional: true + '@esbuild/linux-ppc64@0.27.2': + optional: true + '@esbuild/linux-ppc64@0.27.3': optional: true @@ -18468,6 +18703,9 @@ snapshots: '@esbuild/linux-riscv64@0.27.0': optional: true + '@esbuild/linux-riscv64@0.27.2': + optional: true + '@esbuild/linux-riscv64@0.27.3': optional: true @@ -18489,6 +18727,9 @@ snapshots: '@esbuild/linux-s390x@0.27.0': optional: true + '@esbuild/linux-s390x@0.27.2': + optional: true + '@esbuild/linux-s390x@0.27.3': optional: true @@ -18510,6 +18751,9 @@ snapshots: '@esbuild/linux-x64@0.27.0': optional: true + '@esbuild/linux-x64@0.27.2': + optional: true + '@esbuild/linux-x64@0.27.3': optional: true @@ -18525,6 +18769,9 @@ snapshots: '@esbuild/netbsd-arm64@0.27.0': optional: true + '@esbuild/netbsd-arm64@0.27.2': + optional: true + '@esbuild/netbsd-arm64@0.27.3': optional: true @@ -18546,6 +18793,9 @@ snapshots: '@esbuild/netbsd-x64@0.27.0': optional: true + '@esbuild/netbsd-x64@0.27.2': + optional: true + '@esbuild/netbsd-x64@0.27.3': optional: true @@ -18561,6 +18811,9 @@ snapshots: '@esbuild/openbsd-arm64@0.27.0': optional: true + '@esbuild/openbsd-arm64@0.27.2': + optional: true + '@esbuild/openbsd-arm64@0.27.3': optional: true @@ -18582,6 +18835,9 @@ snapshots: '@esbuild/openbsd-x64@0.27.0': optional: true + '@esbuild/openbsd-x64@0.27.2': + optional: true + '@esbuild/openbsd-x64@0.27.3': optional: true @@ -18594,6 +18850,9 @@ snapshots: '@esbuild/openharmony-arm64@0.27.0': optional: true + '@esbuild/openharmony-arm64@0.27.2': + optional: true + '@esbuild/openharmony-arm64@0.27.3': optional: true @@ -18615,6 +18874,9 @@ snapshots: '@esbuild/sunos-x64@0.27.0': optional: true + '@esbuild/sunos-x64@0.27.2': + optional: true + '@esbuild/sunos-x64@0.27.3': optional: true @@ -18636,6 +18898,9 @@ snapshots: '@esbuild/win32-arm64@0.27.0': optional: true + '@esbuild/win32-arm64@0.27.2': + optional: true + '@esbuild/win32-arm64@0.27.3': optional: true @@ -18657,6 +18922,9 @@ snapshots: '@esbuild/win32-ia32@0.27.0': optional: true + '@esbuild/win32-ia32@0.27.2': + optional: true + '@esbuild/win32-ia32@0.27.3': optional: true @@ -18678,6 +18946,9 @@ snapshots: '@esbuild/win32-x64@0.27.0': optional: true + '@esbuild/win32-x64@0.27.2': + optional: true + '@esbuild/win32-x64@0.27.3': optional: true @@ -19089,128 +19360,128 @@ snapshots: '@inquirer/ansi@1.0.2': {} - '@inquirer/checkbox@4.3.2(@types/node@25.9.5)': + '@inquirer/checkbox@4.3.2(@types/node@24.3.0)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@24.3.0) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/confirm@5.1.21(@types/node@25.9.5)': + '@inquirer/confirm@5.1.21(@types/node@24.3.0)': dependencies: - '@inquirer/core': 10.3.2(@types/node@25.9.5) - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@24.3.0) optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/core@10.3.2(@types/node@25.9.5)': + '@inquirer/core@10.3.2(@types/node@24.3.0)': dependencies: '@inquirer/ansi': 1.0.2 '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@24.3.0) 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': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/editor@4.2.23(@types/node@25.9.5)': + '@inquirer/editor@4.2.23(@types/node@24.3.0)': dependencies: - '@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) + '@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) optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/expand@4.0.23(@types/node@25.9.5)': + '@inquirer/expand@4.0.23(@types/node@24.3.0)': dependencies: - '@inquirer/core': 10.3.2(@types/node@25.9.5) - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@24.3.0) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/external-editor@1.0.3(@types/node@25.9.5)': + '@inquirer/external-editor@1.0.3(@types/node@24.3.0)': dependencies: chardet: 2.1.1 iconv-lite: 0.7.2 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 '@inquirer/figures@1.0.15': {} - '@inquirer/input@4.3.1(@types/node@25.9.5)': + '@inquirer/input@4.3.1(@types/node@24.3.0)': dependencies: - '@inquirer/core': 10.3.2(@types/node@25.9.5) - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@24.3.0) optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/number@3.0.23(@types/node@25.9.5)': + '@inquirer/number@3.0.23(@types/node@24.3.0)': dependencies: - '@inquirer/core': 10.3.2(@types/node@25.9.5) - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@24.3.0) optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/password@4.0.23(@types/node@25.9.5)': + '@inquirer/password@4.0.23(@types/node@24.3.0)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@25.9.5) - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@24.3.0) optionalDependencies: - '@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) + '@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) optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/rawlist@4.1.11(@types/node@25.9.5)': + '@inquirer/rawlist@4.1.11(@types/node@24.3.0)': dependencies: - '@inquirer/core': 10.3.2(@types/node@25.9.5) - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@24.3.0) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/search@3.2.2(@types/node@25.9.5)': + '@inquirer/search@3.2.2(@types/node@24.3.0)': dependencies: - '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@24.3.0) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/select@4.4.2(@types/node@25.9.5)': + '@inquirer/select@4.4.2(@types/node@24.3.0)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/core': 10.3.2(@types/node@24.3.0) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@24.3.0) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 - '@inquirer/type@3.0.10(@types/node@25.9.5)': + '@inquirer/type@3.0.10(@types/node@24.3.0)': optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 '@internationalized/date@3.10.0': dependencies: @@ -19328,10 +19599,10 @@ snapshots: '@leichtgewicht/ip-codec@2.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)': + '@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)': dependencies: - '@inquirer/prompts': 7.10.1(@types/node@25.9.5) - '@inquirer/type': 3.0.10(@types/node@25.9.5) + '@inquirer/prompts': 7.10.1(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@24.3.0) listr2: 9.0.5 transitivePeerDependencies: - '@types/node' @@ -19554,7 +19825,7 @@ snapshots: '@tybys/wasm-util': 0.10.1 optional: true - '@noble/hashes@2.3.0': {} + '@noble/hashes@2.4.0': {} '@node-rs/jieba-android-arm-eabi@1.10.4': optional: true @@ -19761,11 +20032,11 @@ snapshots: '@nuxt/devalue@2.0.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-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))': dependencies: '@nuxt/kit': 3.21.1(magicast@0.3.5) execa: 8.0.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) + 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) transitivePeerDependencies: - magicast @@ -19780,12 +20051,12 @@ snapshots: prompts: 2.4.2 semver: 7.7.4 - '@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/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))': dependencies: - '@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-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-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@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-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-kit': 7.7.9 birpc: 2.9.0 consola: 3.4.2 @@ -19810,9 +20081,9 @@ snapshots: sirv: 3.0.2 structured-clone-es: 1.0.0 tinyglobby: 0.2.15 - 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)) + 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)) which: 5.0.0 ws: 8.18.3 transitivePeerDependencies: @@ -19890,12 +20161,12 @@ snapshots: rc9: 3.0.0 std-env: 3.10.0 - '@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)': + '@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)': 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@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)) + '@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)) autoprefixer: 10.4.21(postcss@8.5.6) consola: 3.4.2 cssnano: 7.1.2(postcss@8.5.6) @@ -19921,9 +20192,9 @@ snapshots: ufo: 1.6.3 unenv: 2.0.0-rc.24 unplugin: 2.3.11 - 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)) + 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)) vue: 3.5.26(typescript@5.6.3) vue-bundle-renderer: 2.2.0 transitivePeerDependencies: @@ -20873,7 +21144,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@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)': + '@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)': dependencies: '@babel/core': 7.28.6 '@babel/generator': 7.28.6 @@ -20890,7 +21161,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@25.9.5)(sass@1.97.3)(terser@5.43.1) + '@vanilla-extract/integration': 6.5.0(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) arg: 5.0.2 cacache: 17.1.4 chalk: 4.1.2 @@ -20918,7 +21189,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@25.9.5)(typescript@5.6.3)) + 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-modules: 6.0.1(postcss@8.5.6) prettier: 2.8.8 pretty-ms: 7.0.1 @@ -20929,13 +21200,13 @@ snapshots: set-cookie-parser: 2.7.2 tar-fs: 2.1.4 tsconfig-paths: 4.2.0 - 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) + 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) 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@25.9.5)(sass@1.97.3)(terser@5.43.1) + vite: 5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -21480,25 +21751,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@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))': + '@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))': dependencies: - '@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)) + '@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)) debug: 4.4.3 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) + 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) transitivePeerDependencies: - supports-color - '@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))': + '@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))': 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@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)) + '@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)) 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@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)) + 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)) transitivePeerDependencies: - supports-color @@ -21686,19 +21957,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.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/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)': 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.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-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-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.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) transitivePeerDependencies: - '@rsbuild/core' - crossws @@ -21740,12 +22011,12 @@ snapshots: prettier: 3.6.2 recast: 0.23.11 source-map: 0.7.6 - tsx: 4.23.12 + tsx: 4.21.0 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.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-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)': dependencies: '@babel/core': 7.29.0 '@babel/plugin-syntax-jsx': 7.27.1(@babel/core@7.29.0) @@ -21762,8 +22033,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.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)) + 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)) webpack: 5.102.0 transitivePeerDependencies: - supports-color @@ -21798,7 +22069,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.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-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)': dependencies: '@babel/code-frame': 7.27.1 '@babel/core': 7.29.0 @@ -21806,7 +22077,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.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-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-utils': 1.161.4 '@tanstack/start-client-core': 1.162.6 '@tanstack/start-server-core': 1.162.6 @@ -21818,8 +22089,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.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)) + 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)) xmlbuilder2: 4.0.3 zod: 3.25.76 transitivePeerDependencies: @@ -21957,9 +22228,9 @@ snapshots: dependencies: bun-types: 1.3.9 - '@types/bun@1.4.1': + '@types/bun@1.4.2': dependencies: - bun-types: 1.4.1 + bun-types: 1.4.2 '@types/chai@5.2.2': dependencies: @@ -22106,9 +22377,9 @@ snapshots: dependencies: undici-types: 6.21.0 - '@types/node@25.9.5': + '@types/node@24.3.0': dependencies: - undici-types: 7.24.6 + undici-types: 7.10.0 optional: true '@types/object-inspect@1.13.0': {} @@ -22425,7 +22696,7 @@ snapshots: transitivePeerDependencies: - babel-plugin-macros - '@vanilla-extract/integration@6.5.0(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1)': + '@vanilla-extract/integration@6.5.0(@types/node@24.3.0)(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) @@ -22438,8 +22709,8 @@ snapshots: lodash: 4.17.21 mlly: 1.8.0 outdent: 0.8.0 - 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) + 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) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -22475,11 +22746,11 @@ snapshots: '@vercel/oidc@3.0.3': {} - '@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))': + '@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))': dependencies: - 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: 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-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))': + '@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))': dependencies: '@babel/core': 7.28.3 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.3) @@ -22487,11 +22758,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.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) transitivePeerDependencies: - supports-color - '@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))': + '@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))': dependencies: '@babel/core': 7.28.3 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.3) @@ -22499,11 +22770,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@25.9.5)(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@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) transitivePeerDependencies: - supports-color - '@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))': + '@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))': dependencies: '@babel/core': 7.28.3 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.3) @@ -22511,27 +22782,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@25.9.5)(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@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) transitivePeerDependencies: - supports-color - '@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))': + '@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))': 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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + 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) transitivePeerDependencies: - supports-color - '@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@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))': dependencies: - 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: 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) - '@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))': + '@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))': dependencies: '@ampproject/remapping': 2.3.0 '@bcoe/v8-coverage': 1.0.2 @@ -22546,7 +22817,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.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) transitivePeerDependencies: - supports-color @@ -22558,21 +22829,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.23.12)(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.21.0)(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.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) - '@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/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))': dependencies: '@vitest/spy': 3.2.4 estree-walker: 3.0.3 magic-string: 0.30.19 optionalDependencies: - 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: 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/pretty-format@3.2.4': dependencies: @@ -22719,14 +22990,14 @@ snapshots: '@vue/devtools-api@6.6.4': {} - '@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-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))': 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@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)) vue: 3.5.26(typescript@5.6.3) transitivePeerDependencies: - vite @@ -24276,7 +24547,7 @@ snapshots: dependencies: '@types/node': 22.18.0 - bun-types@1.4.1: + bun-types@1.4.2: dependencies: '@types/node': 22.18.0 @@ -25027,10 +25298,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.4.1)(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.2)(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.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.2)(pg@8.18.0)(sql.js@1.14.0) de-indent@1.0.2: {} @@ -25216,14 +25487,14 @@ snapshots: 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): + 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.2)(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.4.1 + bun-types: 1.4.2 pg: 8.18.0 sql.js: 1.14.0 optional: true @@ -25483,6 +25754,35 @@ 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 @@ -28578,7 +28878,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.4.1)(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.2)(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) @@ -28599,7 +28899,7 @@ 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.4.1)(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.2)(pg@8.18.0)(sql.js@1.14.0)) defu: 6.1.4 destr: 2.0.5 dot-prop: 10.1.0 @@ -28645,7 +28945,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.4.1)(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.2)(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 @@ -28851,15 +29151,15 @@ snapshots: schema-utils: 3.3.0 webpack: 5.102.0 - 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): + 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.4.2)(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.2)(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): 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@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/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/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@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) + '@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) '@oxc-parser/wasm': 0.60.0 '@unhead/vue': 2.1.4(vue@3.5.26(typescript@5.6.3)) '@vue/shared': 3.5.26 @@ -28888,7 +29188,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.4.1)(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.2)(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 @@ -28910,7 +29210,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.4.1)(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.2)(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 @@ -28918,7 +29218,7 @@ snapshots: vue-router: 4.6.4(vue@3.5.26(typescript@5.6.3)) optionalDependencies: '@parcel/watcher': 2.5.6 - '@types/node': 25.9.5 + '@types/node': 24.3.0 transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -29641,21 +29941,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@25.9.5)(typescript@5.6.3)): + postcss-load-config@4.0.2(postcss@8.5.6)(ts-node@10.9.2(@types/node@24.3.0)(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@25.9.5)(typescript@5.6.3) + ts-node: 10.9.2(@types/node@24.3.0)(typescript@5.6.3) - postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.23.12)(yaml@2.8.2): + postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(yaml@2.8.2): dependencies: lilconfig: 3.1.3 optionalDependencies: jiti: 2.6.1 postcss: 8.5.6 - tsx: 4.23.12 + tsx: 4.21.0 yaml: 2.8.2 postcss-loader@7.3.4(postcss@8.5.6)(typescript@5.6.3)(webpack@5.102.0): @@ -31816,14 +32116,14 @@ snapshots: v8-compile-cache-lib: 3.0.1 yn: 3.1.1 - ts-node@10.9.2(@types/node@25.9.5)(typescript@5.6.3): + ts-node@10.9.2(@types/node@24.3.0)(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': 25.9.5 + '@types/node': 24.3.0 acorn: 8.15.0 acorn-walk: 8.3.4 arg: 4.1.3 @@ -31853,7 +32153,7 @@ snapshots: tslib@2.8.1: {} - tsup@8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.23.12)(typescript@5.9.3)(yaml@2.8.2): + tsup@8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.2): dependencies: bundle-require: 5.1.0(esbuild@0.25.9) cac: 6.7.14 @@ -31864,7 +32164,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.23.12)(yaml@2.8.2) + postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(yaml@2.8.2) resolve-from: 5.0.0 rollup: 4.50.2 source-map: 0.8.0-beta.0 @@ -31883,17 +32183,11 @@ snapshots: tsx@4.21.0: dependencies: - esbuild: 0.27.3 + esbuild: 0.27.2 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 @@ -31984,7 +32278,7 @@ snapshots: undici-types@6.21.0: {} - undici-types@7.24.6: + undici-types@7.10.0: optional: true undici@6.21.3: {} @@ -32201,7 +32495,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.4.1)(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.2)(pg@8.18.0)(sql.js@1.14.0)))(ioredis@5.9.2): dependencies: anymatch: 3.1.3 chokidar: 5.0.0 @@ -32212,7 +32506,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.4.1)(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.2)(pg@8.18.0)(sql.js@1.14.0)) ioredis: 5.9.2 untun@0.1.3: @@ -32351,7 +32645,7 @@ snapshots: v8-compile-cache-lib@3.0.1: {} - valibot@1.4.2(typescript@5.6.3): + valibot@1.2.0(typescript@5.6.3): optionalDependencies: typescript: 5.6.3 @@ -32400,23 +32694,23 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - 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)): + 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)): dependencies: birpc: 2.9.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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(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-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)): + 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)): dependencies: - 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: 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-node@1.6.1(@types/node@25.9.5)(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): dependencies: cac: 6.7.14 debug: 4.4.3 pathe: 1.1.2 picocolors: 1.1.1 - vite: 5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) + vite: 5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) transitivePeerDependencies: - '@types/node' - less @@ -32428,13 +32722,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.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.21.0)(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.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) transitivePeerDependencies: - '@types/node' - jiti @@ -32449,13 +32743,13 @@ snapshots: - tsx - yaml - 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-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): 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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(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) transitivePeerDependencies: - '@types/node' - jiti @@ -32470,7 +32764,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@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)): + 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)): dependencies: '@babel/code-frame': 7.28.6 chokidar: 4.0.3 @@ -32480,7 +32774,7 @@ snapshots: strip-ansi: 7.1.2 tiny-invariant: 1.3.3 tinyglobby: 0.2.15 - 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: 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) vscode-uri: 3.1.0 optionalDependencies: eslint: 9.33.0(jiti@2.6.1) @@ -32488,7 +32782,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@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@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): dependencies: ansis: 4.2.0 debug: 4.4.3 @@ -32498,14 +32792,14 @@ snapshots: perfect-debounce: 2.1.0 sirv: 3.0.2 unplugin-utils: 0.3.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) - 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)) + 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)) 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.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.21.0)(yaml@2.8.2)): dependencies: '@babel/core': 7.29.0 '@types/babel__core': 7.20.5 @@ -32513,15 +32807,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.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)) + 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)) 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@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@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)): dependencies: '@babel/core': 7.29.0 '@types/babel__core': 7.20.5 @@ -32529,46 +32823,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@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)) + 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)) optionalDependencies: '@testing-library/jest-dom': 6.7.0 transitivePeerDependencies: - supports-color - 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)): + 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)): 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@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(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) 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.23.12)(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.21.0)(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.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) transitivePeerDependencies: - supports-color - typescript - vite@5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1): + vite@5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1): dependencies: esbuild: 0.21.5 postcss: 8.5.6 rollup: 4.56.0 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 fsevents: 2.3.3 sass: 1.97.3 terser: 5.43.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): + 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): dependencies: esbuild: 0.25.9 fdir: 6.5.0(picomatch@4.0.3) @@ -32577,15 +32871,15 @@ snapshots: rollup: 4.56.0 tinyglobby: 0.2.15 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 fsevents: 2.3.3 jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.23.12 + 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@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): dependencies: esbuild: 0.25.9 fdir: 6.5.0(picomatch@4.0.3) @@ -32599,10 +32893,10 @@ snapshots: jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.23.12 + 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@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): dependencies: esbuild: 0.25.9 fdir: 6.5.0(picomatch@4.0.3) @@ -32611,15 +32905,15 @@ snapshots: rollup: 4.50.2 tinyglobby: 0.2.15 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 fsevents: 2.3.3 jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.23.12 + 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): + 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): dependencies: esbuild: 0.27.3 fdir: 6.5.0(picomatch@4.0.4) @@ -32633,10 +32927,10 @@ snapshots: jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.23.12 + 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@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): dependencies: esbuild: 0.27.3 fdir: 6.5.0(picomatch@4.0.4) @@ -32645,31 +32939,31 @@ snapshots: rollup: 4.56.0 tinyglobby: 0.2.15 optionalDependencies: - '@types/node': 25.9.5 + '@types/node': 24.3.0 fsevents: 2.3.3 jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.23.12 + 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)): + 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)): optionalDependencies: - 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: 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@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.21.0)(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.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) - 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)): + 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)): optionalDependencies: - 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: 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) - 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): + 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): 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.23.12)(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.21.0)(yaml@2.8.2)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -32687,8 +32981,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.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) + 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) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.12 @@ -32708,11 +33002,11 @@ snapshots: - tsx - yaml - 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): + 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): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@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/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/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -32730,12 +33024,12 @@ snapshots: tinyglobby: 0.2.15 tinypool: 1.1.1 tinyrainbow: 2.0.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) - 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: 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) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.12 - '@types/node': 25.9.5 + '@types/node': 24.3.0 jsdom: 26.1.0 transitivePeerDependencies: - jiti From 365e8dd4b0365db27b135a3303fea0aca9fafe34 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:17:40 -0400 Subject: [PATCH 09/32] Refuse to remove the last rate-limit admin --- spacetime-rate-limit-ts/README.md | 3 ++- spacetime-rate-limit-ts/src/limit.ts | 1 + spacetime-rate-limit-ts/src/submodule/operations.ts | 7 ++++++- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index c88d2c8c781..07027714265 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -112,7 +112,8 @@ Override limits or windows only for application-owned dynamic policies. `install(ctx, { sweepBatch?, sweepIntervalSeconds? })` seeds the publishing identity and cleanup timer from the host's `init` reducer. Repeated installation does not add administrators or timers. Admins can grant and revoke access with -`addRateLimitAdmin` and `removeRateLimitAdmin`. +`addRateLimitAdmin` and `removeRateLimitAdmin`. The last administrator cannot be +removed. `errors` exports stable error codes for callers that distinguish failures. diff --git a/spacetime-rate-limit-ts/src/limit.ts b/spacetime-rate-limit-ts/src/limit.ts index 9806aa57c67..974a2f15cb1 100644 --- a/spacetime-rate-limit-ts/src/limit.ts +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -10,6 +10,7 @@ const DEFAULT_SWEEP_INTERVAL_SECONDS = 30n; export const errors = { notAuthorized: 'rate_limit.not_authorized', + cannotRemoveLastAdmin: 'rate_limit.cannot_remove_last_admin', invalidScope: 'rate_limit.invalid_scope', invalidActorKey: 'rate_limit.invalid_actor_key', invalidLimit: 'rate_limit.invalid_limit', diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts index 57e50234ae3..29c6be9a9e5 100644 --- a/spacetime-rate-limit-ts/src/submodule/operations.ts +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -144,7 +144,12 @@ export const removeRateLimitAdmin = spacetimedb.reducer( { identity: t.identity() }, (ctx, { identity }) => { requireAdmin(ctx); - ctx.db.rateLimitAdminIdentity.identity.delete(identity); + const existing = ctx.db.rateLimitAdminIdentity.identity.find(identity); + if (!existing) return; + if (ctx.db.rateLimitAdminIdentity.count() <= 1n) { + throw new SenderError(errors.cannotRemoveLastAdmin); + } + ctx.db.rateLimitAdminIdentity.delete(existing); } ); From 36e058d07a6038b6b8544396564459d2bae89ce3 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:20:14 -0400 Subject: [PATCH 10/32] Install rate limit with install(ctx) and bound maintenance batches alike Drop the install options, the standalone install and sweep exports, and helpers exported only for tests. runSweep and resetBuckets share one maxRows validation. --- spacetime-rate-limit-ts/README.md | 29 ++--- spacetime-rate-limit-ts/scripts/test.ts | 13 --- spacetime-rate-limit-ts/src/index.ts | 4 - spacetime-rate-limit-ts/src/limit.ts | 100 +----------------- spacetime-rate-limit-ts/src/submodule.ts | 1 - .../src/submodule/install.ts | 32 ++++-- .../src/submodule/operations.ts | 28 ++--- .../src/submodule/schema.ts | 4 - 8 files changed, 48 insertions(+), 163 deletions(-) diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index 07027714265..2a224d5d396 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -8,8 +8,6 @@ Fixed-window rate limiter submodule for SpacetimeDB TypeScript modules. 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/). @@ -109,11 +107,11 @@ Configure a policy once with `client({ scope, limit, windowSeconds })`. Call transaction. `key` identifies the actor; the library combines it with the scope. Override limits or windows only for application-owned dynamic policies. -`install(ctx, { sweepBatch?, sweepIntervalSeconds? })` seeds the publishing -identity and cleanup timer from the host's `init` reducer. Repeated installation -does not add administrators or timers. Admins can grant and revoke access with -`addRateLimitAdmin` and `removeRateLimitAdmin`. The last administrator cannot be -removed. +`install(ctx)` makes the publishing identity the first administrator and +schedules a sweep of expired buckets every 30 seconds. Call it from the host's +`init` reducer. Repeated installation does not add administrators or timers. +Admins can grant and revoke access with `addRateLimitAdmin` and +`removeRateLimitAdmin`. The last administrator cannot be removed. `errors` exports stable error codes for callers that distinguish failures. @@ -121,17 +119,13 @@ The root package also exports lower-level helpers for standalone integrations: - `consumeRateLimit` - `buildRateLimitKey` -- `installRateLimitState` -- `sweepRateLimits` The submodule `consume`, `runSweep`, and `resetBuckets` operations are admin-only. Application-facing operations should enforce a fixed policy in host code and use -the configured limiter shown above. `resetBuckets({ 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`. +the configured limiter shown above. `runSweep({ maxRows })` and +`resetBuckets({ maxRows })` remove 500 rows by default and accept at most 10,000 +per call. `updateConfig({ sweepBatch })` sets how many expired rows each +scheduled sweep deletes, with the same default and maximum. Package entrypoints: @@ -143,11 +137,6 @@ See the [Powerhouse host module](./example/spacetimedb/) for per-action policies, caller-visible status, and admin controls. -## Cleanup defaults - -- 500 expired rows per sweep; at most 10,000. -- One sweep every 30 seconds. - Use `buildRateLimitKey(scope, actorKey)` only when reading an existing bucket for a status view. Consuming a configured policy does not require constructing keys. diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts index fe365e7172e..daa20953de1 100644 --- a/spacetime-rate-limit-ts/scripts/test.ts +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -2,9 +2,7 @@ import { Timestamp } from 'spacetimedb'; import { consumeRateLimit, client, - DEFAULT_SWEEP_BATCH, MAX_SWEEP_BATCH, - resolveRateLimitSweepBatch, sweepRateLimits, type RateLimitBucketRow, } from '../src/limit.ts'; @@ -149,17 +147,6 @@ process.stdout.write('\nrate limiter\n'); '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( diff --git a/spacetime-rate-limit-ts/src/index.ts b/spacetime-rate-limit-ts/src/index.ts index 50569d74676..0e5119df8bf 100644 --- a/spacetime-rate-limit-ts/src/index.ts +++ b/spacetime-rate-limit-ts/src/index.ts @@ -2,12 +2,8 @@ export { client, errors, consumeRateLimit, - installRateLimitState, - sweepRateLimits, type ConsumeRateLimitOpts, type RateLimitPolicy, - type RateLimitInstallOpts, - type RateLimitInitCtxLike, type RateLimitResult, type RateLimitTxLike, } from './limit'; diff --git a/spacetime-rate-limit-ts/src/limit.ts b/spacetime-rate-limit-ts/src/limit.ts index 974a2f15cb1..ccf3db0bf8f 100644 --- a/spacetime-rate-limit-ts/src/limit.ts +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -1,4 +1,4 @@ -import { ScheduleAt, Timestamp } from 'spacetimedb'; +import { Timestamp } from 'spacetimedb'; import { buildRateLimitKey } from './key'; const ONE_SECOND_MICROS = 1_000_000n; @@ -6,7 +6,6 @@ const U32_MAX = 0xffff_ffff; export const DEFAULT_SWEEP_BATCH = 500; export const MAX_SWEEP_BATCH = 10_000; -const DEFAULT_SWEEP_INTERVAL_SECONDS = 30n; export const errors = { notAuthorized: 'rate_limit.not_authorized', @@ -17,7 +16,7 @@ export const errors = { invalidWindow: 'rate_limit.invalid_window', invalidCost: 'rate_limit.invalid_cost', invalidSweepBatch: 'rate_limit.invalid_sweep_batch', - invalidSweepInterval: 'rate_limit.invalid_sweep_interval_seconds', + invalidMaxRows: 'rate_limit.invalid_max_rows', configMissing: 'rate_limit.config_missing', } as const; @@ -92,7 +91,7 @@ function assertPositiveInt(code: string, value: number): void { } } -export function assertRateLimitSweepBatch(value: number): void { +function assertRateLimitSweepBatch(value: number): void { assertPositiveInt(errors.invalidSweepBatch, value); if (value > MAX_SWEEP_BATCH) { throw new Error(errors.invalidSweepBatch); @@ -137,99 +136,6 @@ export interface RateLimitTxLike { }; } -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(errors.invalidSweepInterval); - - const existing = ctx.db.rateLimitConfig.singleton.find(true); - if (existing) return; - 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 diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts index 1792378916b..9959d2e0ac3 100644 --- a/spacetime-rate-limit-ts/src/submodule.ts +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -6,7 +6,6 @@ export { consumeRateLimit, type ConsumeRateLimitOpts, type RateLimitPolicy, - type RateLimitInstallOpts, type RateLimitResult, type RateLimitTxLike, } from './limit'; diff --git a/spacetime-rate-limit-ts/src/submodule/install.ts b/spacetime-rate-limit-ts/src/submodule/install.ts index 060f56092e0..7523b7fc953 100644 --- a/spacetime-rate-limit-ts/src/submodule/install.ts +++ b/spacetime-rate-limit-ts/src/submodule/install.ts @@ -1,14 +1,26 @@ -import { installRateLimitState, type RateLimitInstallOpts } from '../limit'; +import { ScheduleAt } from 'spacetimedb'; +import { DEFAULT_SWEEP_BATCH } from '../limit'; import type { ReducerModuleCtx } from './schema'; -/** Call from the host's init reducer to seed its publishing identity and cleanup timer. */ -export function install(ctx: ReducerModuleCtx, opts?: RateLimitInstallOpts) { +const SWEEP_INTERVAL_MICROS = 30_000_000n; + +/** + * Call from the host's init reducer. Makes the publishing identity the first + * administrator and schedules the expired-bucket sweep. Later calls do nothing. + */ +export function install(ctx: ReducerModuleCtx) { if (ctx.db.rateLimitConfig.singleton.find(true)) return; - if (ctx.db.rateLimitAdminIdentity.identity.find(ctx.sender) == null) { - ctx.db.rateLimitAdminIdentity.insert({ - identity: ctx.sender, - addedAt: ctx.timestamp, - }); - } - installRateLimitState(ctx, opts); + ctx.db.rateLimitAdminIdentity.insert({ + identity: ctx.sender, + addedAt: ctx.timestamp, + }); + ctx.db.rateLimitConfig.insert({ + singleton: true, + sweepBatch: DEFAULT_SWEEP_BATCH, + updatedAt: ctx.timestamp, + }); + ctx.db.rateLimitSweepTick.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval(SWEEP_INTERVAL_MICROS), + }); } diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts index 29c6be9a9e5..7c2e0a7e814 100644 --- a/spacetime-rate-limit-ts/src/submodule/operations.ts +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -3,7 +3,6 @@ import { consumeRateLimit, DEFAULT_SWEEP_BATCH, MAX_SWEEP_BATCH, - runRateLimitSweep, sweepRateLimits, errors, } from '../limit'; @@ -20,7 +19,7 @@ import { buildRateLimitKey } from '../key'; const MAX_SCOPE_LENGTH = 128; const MAX_ACTOR_KEY_LENGTH = 256; -export const consumeResult = t.object('RateLimitConsumeResult', { +const consumeResult = t.object('RateLimitConsumeResult', { allowed: t.bool(), scope: t.string(), key: t.string(), @@ -48,6 +47,12 @@ function toU32(code: string, value: number, max = 0xffff_ffff): number { return value; } +function maxRowsArg(value: number | undefined): number { + return value === undefined + ? DEFAULT_SWEEP_BATCH + : toU32(errors.invalidMaxRows, value, MAX_SWEEP_BATCH); +} + function sanitizePart(s: string): string { return s.trim().replace(/\s+/g, ' '); } @@ -106,14 +111,7 @@ export const runSweep = spacetimedb.procedure( { maxRows: t.option(t.u32()) }, t.u32(), (ctx, args) => { - const maxRows = - args.maxRows === undefined - ? undefined - : toU32( - errors.invalidSweepBatch, - Number(args.maxRows), - MAX_SWEEP_BATCH - ); + const maxRows = maxRowsArg(args.maxRows); return ctx.withTx(tx => { requireAdmin(tx); return sweepRateLimits( @@ -121,7 +119,7 @@ export const runSweep = spacetimedb.procedure( tx.db.rateLimitBucket.expiresAt.filter( new Range(undefined, { tag: 'included', value: tx.timestamp }) ), - maxRows ?? DEFAULT_SWEEP_BATCH + maxRows ); }); } @@ -175,7 +173,7 @@ export const resetBuckets = spacetimedb.reducer( { maxRows: t.option(t.u32()) }, (ctx, args) => { requireAdmin(ctx); - const maxRows = Math.min(Number(args.maxRows ?? 1000), 10_000); + const maxRows = maxRowsArg(args.maxRows); let removed = 0; for (const row of ctx.db.rateLimitBucket.iter()) { if (removed >= maxRows) break; @@ -203,11 +201,13 @@ export const rateLimitSweep = spacetimedb.reducer( { onSchedule: rateLimitSweepTick }, { arg: rateLimitSweepTick.rowType }, (ctx, _args) => { - runRateLimitSweep( + sweepRateLimits( ctx, ctx.db.rateLimitBucket.expiresAt.filter( new Range(undefined, { tag: 'included', value: ctx.timestamp }) - ) + ), + ctx.db.rateLimitConfig.singleton.find(true)?.sweepBatch ?? + DEFAULT_SWEEP_BATCH ); } ); diff --git a/spacetime-rate-limit-ts/src/submodule/schema.ts b/spacetime-rate-limit-ts/src/submodule/schema.ts index ec4be8b76b1..6e89b4cfcc8 100644 --- a/spacetime-rate-limit-ts/src/submodule/schema.ts +++ b/spacetime-rate-limit-ts/src/submodule/schema.ts @@ -3,9 +3,7 @@ import { table, t, type InferSchema, - type ProcedureCtx, type ReducerCtx, - type TransactionCtx, type ViewCtx, } from 'spacetimedb/server'; @@ -56,8 +54,6 @@ 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 }; From b51ef2ed0fe66cf3f77213b35c681e297f734eb0 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:26:20 -0400 Subject: [PATCH 11/32] Replace createRetrySubmodule with retry client and install client({ handlers }) imports the SDK directly and returns the tables, install, submit, views, and reducers. Contexts are typed against the retry tables instead of unknown, and thrown codes come from an exported errors object. retryHandler no longer defines a property on the caller's type builder, so one builder can back several handlers. The custom auth policy is replaced by submit(), which host reducers call after their own checks. History is written once per attempt with its final status, pruned by removing the oldest row through the ranAt index, and served newest first without sorting. The unused taskName and status indexes are removed, admin rows store addedAt as a timestamp, and the task view returns the newest tasks. --- spacetime-retry-ts/README.md | 94 ++-- spacetime-retry-ts/package.json | 2 +- .../scripts/sys-abi-test-register.mjs | 27 ++ spacetime-retry-ts/scripts/test.ts | 235 ++++++--- spacetime-retry-ts/spacetimedb/src/index.ts | 14 +- spacetime-retry-ts/src/handler.ts | 49 +- spacetime-retry-ts/src/index.ts | 9 +- spacetime-retry-ts/src/submodule.ts | 457 ++++++++---------- spacetime-retry-ts/tsconfig.json | 3 +- 9 files changed, 473 insertions(+), 417 deletions(-) create mode 100644 spacetime-retry-ts/scripts/sys-abi-test-register.mjs diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md index 5fa47884ebd..d2e921af709 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -1,6 +1,6 @@ # @spacetimedb/retry -A typed retry factory for SpacetimeDB TypeScript modules. It creates a private +Typed retries for SpacetimeDB TypeScript modules. `client()` creates a private scheduled-task table, attempt history, admin controls, and exponential-backoff dispatch around handlers defined by the host module. @@ -10,7 +10,7 @@ dispatch around handlers defined by the host module. npm install @spacetimedb/retry spacetimedb ``` -The factory registers its tables and reducers in the host schema. It does not +The tables and reducers are registered in the host schema. Retry does not mount a separate submodule schema. `spacetimedb` is a peer dependency. Keep its version aligned with the SDK used @@ -23,26 +23,16 @@ For the install-to-publish workflow, see ### 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. +The task variants and handlers belong to the host, so `client()` runs when the +module loads, before `schema()`. The example below is a module-definition +skeleton: replace `sendReceipt` with an idempotent application handler. ```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 }, - { +import { schema, t } from 'spacetimedb/server'; +import { client, retryFailed, retryHandler, retryOk } from '@spacetimedb/retry'; + +const retry = client({ + handlers: { sendReceipt: retryHandler( t.object('SendReceiptArgs', { orderId: t.u64() }), (ctx, { orderId }) => { @@ -50,10 +40,14 @@ const retry = createRetrySubmodule( return result.sent ? retryOk() : retryFailed(result.error); } ), - } -); + }, +}); const db = schema({ ...retry.tables }); +export default db; + +export const init = db.init(ctx => retry.install(ctx)); + export const retryFire = db.reducer( { onSchedule: retry.tables.retryTask }, { arg: retry.tables.retryTask.rowType }, @@ -64,11 +58,12 @@ export const submitRetryTask = db.reducer( retry.reducers.submitRetryTask.params, retry.reducers.submitRetryTask.handler ); - -export const init = db.init(ctx => retry.install(ctx)); -export default db; ``` +Register the scheduled reducer after `schema()` so it can reference the +scheduled table. Handlers receive the host's reducer context as `unknown` +because it is defined after the handlers. + Submit tagged arguments with an attempt cap and base backoff. The first attempt is scheduled immediately; subsequent delays are `backoffSecs * 2^attempt`. @@ -83,16 +78,22 @@ view returns these attempts newest first. ## API -- `retryHandler(args, run)` associates a SpacetimeDB type builder with a task +- `client({ handlers })` returns `tables`, `install`, `submit`, + `requireAdmin`, `views`, and `reducers`. +- `install(ctx)` seeds the publishing identity as the initial admin. Call it + from the host's `init` reducer. +- `submit(ctx, task)` validates a task and schedules its first attempt without + an authorization check. Call it from host reducers that authorize the caller. +- `reducers.submitRetryTask`, `reducers.addRetryAdminIdentity`, and + `reducers.removeRetryAdminIdentity` require a Retry admin. +- `views.retryTasksAdmin` and `views.retryHistoryAdmin` return up to 1,000 + pending tasks and attempts, newest first, to Retry admins. +- `retryHandler(args, run)` pairs 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. -- `install(ctx)` seeds the publishing identity as the initial admin. +- `errors` holds the `retry.*` codes thrown by these operations. The generated client can submit a task when the host exports -`submitRetryTask`. The default factory authorization restricts this operation -to Retry administrators: +`submitRetryTask`: ```ts await conn.reducers.submitRetryTask({ @@ -103,14 +104,31 @@ await conn.reducers.submitRetryTask({ }); ``` -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. +Product-facing applications usually expose a narrower reducer that authorizes +the caller, fixes the retry limits, and calls `retry.submit`: + +```ts +export const requestReceipt = db.reducer( + { orderId: t.u64() }, + (ctx, { orderId }) => { + requireOrderOwner(ctx, orderId); + retry.submit(ctx, { + name: `receipt:${orderId}`, + args: { tag: 'sendReceipt', value: { orderId } }, + maxAttempts: 5, + backoffSecs: 2, + }); + } +); +``` + +Operational screens can subscribe to the admin task and history views. Package entrypoints: -- `@spacetimedb/retry/submodule` exports `createRetrySubmodule`. -- `@spacetimedb/retry` exports the factory, handler, dispatch, and result helpers. +- `@spacetimedb/retry` exports `client`, `errors`, and the handler and result + helpers. +- `@spacetimedb/retry/submodule` exports `client` and `errors`. ## Testing @@ -120,7 +138,7 @@ pnpm run lint pnpm --dir spacetimedb run build ``` -The build compiles the fixture module that registers the factory's tables and reducers. +The build compiles the fixture module that registers Retry's tables and reducers. ## License diff --git a/spacetime-retry-ts/package.json b/spacetime-retry-ts/package.json index 1335d34fc0e..2a5a9359bd9 100644 --- a/spacetime-retry-ts/package.json +++ b/spacetime-retry-ts/package.json @@ -44,7 +44,7 @@ "format": "prettier . --write --ignore-path ../.prettierignore", "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", - "test": "tsx scripts/test.ts", + "test": "node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test.ts", "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, diff --git a/spacetime-retry-ts/scripts/sys-abi-test-register.mjs b/spacetime-retry-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..30107456e71 --- /dev/null +++ b/spacetime-retry-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,27 @@ +import { register } from 'node:module'; + +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; + +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; + export function resolve(specifier, context, nextResolve) { + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts index adae425329d..f400b1d26e1 100644 --- a/spacetime-retry-ts/scripts/test.ts +++ b/spacetime-retry-ts/scripts/test.ts @@ -1,84 +1,149 @@ 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'; +import { Identity, Timestamp } from 'spacetimedb'; +import { ScheduleAt, t } from 'spacetimedb/server'; +import { client, errors, retryFailed, retryHandler, retryOk } from '../src'; 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 }, - { +const sharedArgs = t.object('TestArgs', { value: t.string() }); +const retry = client({ + handlers: { throws: retryHandler(t.unit(), () => { throw new Error('x'.repeat(3000)); }), fails: retryHandler(t.unit(), () => retryFailed('unavailable')), succeeds: retryHandler(t.unit(), () => retryOk()), + // One argument builder may back several handlers. + first: retryHandler(sharedArgs, (_ctx, args) => { + calls.push(`first:${args.value}`); + return retryOk(); + }), + second: retryHandler(sharedArgs, (_ctx, args) => { + calls.push(`second:${args.value}`); + return retryOk(); + }), }, - { isAdmin: () => true } -); +}); + type Task = Parameters[1]['arg']; type History = ReturnType[number]; +type Ctx = Parameters[0]; + +const admin = Identity.zero(); +const stranger = new Identity(1n); +const admins = new Map(); const history = new Map(); -const scheduled: Task[] = []; -let nextId = 0n; -const ctx = { - timestamp: new Timestamp(10_000_000n), +const tasks = new Map(); +let nextHistoryId = 0n; +let nextTaskId = 0n; +let sender = admin; +let now = 10_000_000n; + +const byRanAt = () => + [...history.values()] + .sort((a, b) => + a.ranAt.microsSinceUnixEpoch === b.ranAt.microsSinceUnixEpoch + ? Number(a.id - b.id) + : Number(a.ranAt.microsSinceUnixEpoch - b.ranAt.microsSinceUnixEpoch) + ) + .values(); + +const ctx: Ctx = { + get sender() { + return sender; + }, + get timestamp() { + return new Timestamp(now); + }, db: { - retryTask: { insert: (row: Task) => scheduled.push(row) }, + retryTask: { + name: { + filter: (name: string) => + [...tasks.values()].filter(row => row.name === name).values(), + }, + iter: () => tasks.values(), + insert(row: Task) { + const inserted = { ...row, scheduledId: ++nextTaskId }; + tasks.set(inserted.scheduledId, inserted); + return inserted; + }, + }, retryHistory: { + ranAt: { filter: byRanAt }, insert(row: History) { - const inserted = { ...row, id: ++nextId }; + const inserted = { ...row, id: ++nextHistoryId }; history.set(inserted.id, inserted); return inserted; }, - id: { - update: (row: History) => history.set(row.id, row), - delete: (id: bigint) => history.delete(id), + delete: (row: History) => history.delete(row.id), + count: () => BigInt(history.size), + }, + retryAdminIdentity: { + identity: { + find: (identity: Identity) => + admins.get(identity.toHexString()) ?? null, + }, + insert(row: { identity: Identity; addedAt: Timestamp }) { + admins.set(row.identity.toHexString(), row); + return row; }, - iter: () => history.values(), + delete: (row: { identity: Identity }) => + admins.delete(row.identity.toHexString()), + count: () => BigInt(admins.size), }, }, }; + +retry.install(ctx); +assert.equal( + admins.get(admin.toHexString())?.addedAt.microsSinceUnixEpoch, + now +); + +// Submission validates input and requires an admin. +const submit = retry.reducers.submitRetryTask.handler; +const valid = { + name: 'job', + args: { tag: 'first', value: { value: 'payload' } }, + maxAttempts: 3, + backoffSecs: 2, +}; +assert.throws(() => submit(ctx, { ...valid, name: '' }), { + message: errors.invalidTaskName, +}); +assert.throws(() => submit(ctx, { ...valid, maxAttempts: 11 }), { + message: errors.invalidMaxAttempts, +}); +assert.throws(() => submit(ctx, { ...valid, backoffSecs: 0 }), { + message: errors.invalidBackoffSeconds, +}); +submit(ctx, valid); +assert.throws(() => submit(ctx, valid), { + message: `${errors.taskAlreadyExists}:job`, +}); +sender = stranger; +assert.throws(() => submit(ctx, { ...valid, name: 'other' }), { + message: errors.notAuthorized, +}); +assert.deepEqual(retry.views.retryTasksAdmin(ctx), []); + +// Handlers sharing one argument builder dispatch independently. `submit` +// skips the admin check for host reducers that authorize callers themselves. +sender = stranger; +retry.submit(ctx, { + name: 'job2', + args: { tag: 'second', value: { value: 'b' } }, + maxAttempts: 1, + backoffSecs: 1, +}); +sender = admin; +retry.reducers.retryFire(ctx, { arg: tasks.get(1n)! }); +retry.reducers.retryFire(ctx, { arg: tasks.get(2n)! }); +assert.deepEqual(calls, ['first:payload', 'second:b']); + +// Failures back off exponentially, then give up. +tasks.clear(); const task: Task = { - scheduledId: 1n, + scheduledId: 0n, scheduledAt: ScheduleAt.time(0n), name: 'test', args: { tag: 'throws' }, @@ -86,34 +151,56 @@ const task: Task = { maxAttempts: 3, backoffSecs: 2, }; +history.clear(); +nextHistoryId = 0n; 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] }); +const [second] = tasks.values(); +assert.equal(second.attempt, 1); +assert.deepEqual(second.scheduledAt, ScheduleAt.time(now + 2_000_000n)); +retry.reducers.retryFire(ctx, { arg: second }); +const third = [...tasks.values()][1]; +assert.equal(third.attempt, 2); +assert.deepEqual(third.scheduledAt, ScheduleAt.time(now + 4_000_000n)); +retry.reducers.retryFire(ctx, { arg: third }); assert.equal(history.get(3n)?.status.tag, 'GaveUp'); -assert.equal(scheduled.length, 2); -retry.reducers.retryFire(ctx, { - arg: { ...task, args: { tag: 'fails' } }, -}); +assert.equal(tasks.size, 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: 'toString' } } }); +assert.equal(history.get(5n)?.error, `${errors.unknownHandler}:toString`); +assert.equal(tasks.size, 4); + +// The newest pending tasks come first. +assert.deepEqual( + retry.views.retryTasksAdmin(ctx).map(row => row.scheduledId), + [...tasks.keys()].reverse() +); + +// History keeps the latest 1,000 attempts. +for (let i = 0; i < 1000; i++) { + now += 1n; retry.reducers.retryFire(ctx, { arg: { ...task, args: { tag: 'succeeds' } }, }); } -assert.equal(scheduled.length, 3); +assert.equal(tasks.size, 4); assert.equal(history.size, 1000); assert.equal(history.has(5n), false); +assert.equal(history.has(6n), true); const recent = retry.views.retryHistoryAdmin(ctx); assert.equal(recent.length, 1000); -assert.equal(recent[0].id, nextId); +assert.equal(recent[0].id, nextHistoryId); assert.equal(recent[0].status.tag, 'Ok'); -assert.equal(recent.at(-1)?.id, nextId - 999n); +assert.equal(recent.at(-1)?.id, nextHistoryId - 999n); + +// The last admin cannot be removed. +assert.throws( + () => + retry.reducers.removeRetryAdminIdentity.handler(ctx, { identity: admin }), + { message: errors.cannotRemoveLastAdmin } +); -console.log('retry tests passed'); +process.stdout.write('retry tests passed\n'); diff --git a/spacetime-retry-ts/spacetimedb/src/index.ts b/spacetime-retry-ts/spacetimedb/src/index.ts index 5c1b16dbf72..7f3504169d4 100644 --- a/spacetime-retry-ts/spacetimedb/src/index.ts +++ b/spacetime-retry-ts/spacetimedb/src/index.ts @@ -1,7 +1,6 @@ -import { schema, table, t, SenderError } from 'spacetimedb/server'; -import { ScheduleAt } from 'spacetimedb'; +import { schema, table, t } from 'spacetimedb/server'; import { - createRetrySubmodule, + client, retryFailed, retryHandler, retryOk, @@ -51,14 +50,7 @@ const flaky = retryHandler(flakyArgs, (ctx, args): RetryResult => { return retryOk(); }); -const retryHandlers = { - flaky, -}; - -const retry = createRetrySubmodule( - { table, t, SenderError, ScheduleAt }, - retryHandlers -); +const retry = client({ handlers: { flaky } }); const { retryTask, retryHistory, retryAdminIdentity } = retry.tables; const retryMetric = table( diff --git a/spacetime-retry-ts/src/handler.ts b/spacetime-retry-ts/src/handler.ts index 64743407137..e066a0225bc 100644 --- a/spacetime-retry-ts/src/handler.ts +++ b/spacetime-retry-ts/src/handler.ts @@ -1,6 +1,7 @@ -import type { ElementsObj, Infer as InferBuilder } from 'spacetimedb/server'; +import type { Infer, VariantsObj } from 'spacetimedb/server'; + +type ArgsBuilder = VariantsObj[string]; -type TypeBuilderLike = ElementsObj[string]; type IsUnit = [keyof T] extends [never] ? true : false; export type RetryResult = { ok: true } | { ok: false; error: string }; @@ -11,46 +12,20 @@ export const retryFailed = (error: string): RetryResult => ({ error, }); -type RunFn = - IsUnit> extends true +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'); + : (ctx: unknown, args: Infer) => RetryResult; -export type RetryHandler = TB & { - [RUN_KEY]: RunFn; +export type RetryHandler = { + readonly args: TB; + readonly run: RunFn; }; -export function retryHandler( +/** Pair a task argument type with the function that runs one attempt. */ +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.prototype.hasOwnProperty.call(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); - }; + return { args, run }; } diff --git a/spacetime-retry-ts/src/index.ts b/spacetime-retry-ts/src/index.ts index f49751f7aee..522f5db3544 100644 --- a/spacetime-retry-ts/src/index.ts +++ b/spacetime-retry-ts/src/index.ts @@ -1,9 +1,14 @@ export { - makeRetryDispatch, retryFailed, retryHandler, retryOk, type RetryHandler, type RetryResult, } from './handler'; -export { createRetrySubmodule, type RetryHandlers } from './submodule'; +export { + client, + errors, + type RetryArgs, + type RetryConfig, + type RetryHandlers, +} from './submodule'; diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index 7934723687d..d11477ddf31 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -1,46 +1,58 @@ import { - makeRetryDispatch, - retryFailed, - type RetryHandler, - type RetryResult, -} from './handler'; -import type { Identity, ScheduleAt, Timestamp } from 'spacetimedb'; -import type { Infer, VariantsObj } from 'spacetimedb/server'; + Range, + ScheduleAt, + SenderError, + t, + table, + type Infer, + type VariantsObj, +} from 'spacetimedb/server'; +import type { Identity, Timestamp } from 'spacetimedb'; +import { retryFailed, type RetryHandler, type RetryResult } from './handler'; 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; +const MAX_ROWS = 1000; + +export const errors = { + notAuthorized: 'retry.not_authorized', + invalidTaskName: 'retry.invalid_task_name', + invalidMaxAttempts: 'retry.invalid_max_attempts', + invalidBackoffSeconds: 'retry.invalid_backoff_seconds', + taskAlreadyExists: 'retry.task_already_exists', + cannotRemoveLastAdmin: 'retry.cannot_remove_last_admin', + unknownHandler: 'retry.unknown_handler', +} as const; 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 interface RetryConfig { + /** Task variants keyed by tag. Each handler runs one attempt. */ + handlers: H; +} -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); +/** Tagged task arguments for the configured handlers. */ +export type RetryArgs = { + [K in keyof H & string]: H[K]['args'] extends ReturnType + ? { tag: K } + : { tag: K; value: Infer }; +}[keyof H & string]; + +/** Create the retry tables, reducers, and views from the host's handlers. */ +export function client({ + handlers, +}: RetryConfig) { + const variants: VariantsObj = {}; + for (const [tag, handler] of Object.entries(handlers)) { + variants[tag] = handler.args; + } + const retryArgs = t.enum('RetryArgs', variants); const retryTask = table( - { - name: 'retry_task', - public: false, - }, + { name: 'retry_task', public: false }, { scheduledId: t.u64().primaryKey().autoInc(), scheduledAt: t.scheduleAt(), @@ -52,26 +64,13 @@ export function createRetrySubmodule( } ); - 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(), + taskName: t.string(), attempt: t.u8(), - status: retryHistoryStatus.index(), + status: t.enum('RetryHistoryStatus', ['Ok', 'Failed', 'GaveUp']), error: t.option(t.string()), ranAt: t.timestamp().index(), } @@ -81,124 +80,125 @@ export function createRetrySubmodule( { name: 'retry_admin_identity', public: false }, { identity: t.identity().primaryKey(), - addedAtMicros: t.i64(), + addedAt: t.timestamp(), } ); - 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; + type TaskRow = Infer; + type HistoryRow = Infer; + type AdminRow = Infer; + type TaskInput = Pick< + TaskRow, + 'name' | 'args' | 'maxAttempts' | 'backoffSecs' + >; + + /** The parts of a host view context that retry reads. */ + interface RetryViewCtx { + readonly sender: Identity; + readonly db: { + readonly retryTask: { iter(): Iterable }; + readonly retryHistory: { + readonly ranAt: { + filter(range: Range): Iterable; + }; + }; + readonly retryAdminIdentity: { + readonly identity: { find(identity: Identity): AdminRow | null }; }; - retryHistory: { - id: { update(row: RetryHistoryRow): void; delete(id: bigint): boolean }; - insert(row: RetryHistoryRow): RetryHistoryRow; - iter(): Iterable; + }; + } + + /** The parts of a host reducer context that retry reads and writes. */ + interface RetryCtx { + readonly sender: Identity; + readonly timestamp: Timestamp; + readonly db: { + readonly retryTask: { + iter(): Iterable; + readonly name: { + filter(name: string): IteratorObject; + }; + insert(row: TaskRow): TaskRow; }; - retryAdminIdentity: { - identity: { - find(identity: Identity): RetryAdminIdentityRow | null | undefined; + readonly retryHistory: { + readonly ranAt: { + filter( + range: Range + ): IteratorObject; }; - insert(row: RetryAdminIdentityRow): RetryAdminIdentityRow; - delete(row: RetryAdminIdentityRow): void; + insert(row: HistoryRow): HistoryRow; + delete(row: HistoryRow): boolean; + count(): bigint; + }; + readonly retryAdminIdentity: { + readonly identity: { find(identity: Identity): AdminRow | null }; + insert(row: AdminRow): AdminRow; + delete(row: AdminRow): boolean; count(): bigint; }; }; } - function retryContext(ctx: unknown): RetryContext { - return ctx as RetryContext; + function isAdmin(ctx: RetryViewCtx): boolean { + return ctx.db.retryAdminIdentity.identity.find(ctx.sender) != null; } - const dispatchRetry = makeRetryDispatch(handlers); - - function install(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: RetryCtx): void { + if (!isAdmin(ctx)) throw new SenderError(errors.notAuthorized); } - 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 addAdmin(ctx: RetryCtx, identity: Identity): void { + if (ctx.db.retryAdminIdentity.identity.find(identity) == null) { + ctx.db.retryAdminIdentity.insert({ identity, addedAt: ctx.timestamp }); } } - 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 - ); + /** Call from the host's init reducer to seed the publishing identity as admin. */ + function install(ctx: RetryCtx): void { + addAdmin(ctx, ctx.sender); } - function takeRows(rows: Iterable, limit = 1000): T[] { - const out: T[] = []; - for (const row of rows) { - if (out.length >= limit) break; - out.push(row); + function submitTask(ctx: RetryCtx, task: TaskInput): void { + if (task.name.length === 0 || task.name.length > MAX_TASK_NAME_LENGTH) { + throw new SenderError(errors.invalidTaskName); } - 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 - ); + if ( + !Number.isInteger(task.maxAttempts) || + task.maxAttempts < 1 || + task.maxAttempts > MAX_ATTEMPTS + ) { + throw new SenderError(errors.invalidMaxAttempts); + } + if ( + !Number.isInteger(task.backoffSecs) || + task.backoffSecs < 1 || + task.backoffSecs > MAX_BACKOFF_SECONDS + ) { + throw new SenderError(errors.invalidBackoffSeconds); + } + if (!ctx.db.retryTask.name.filter(task.name).next().done) { + throw new SenderError(`${errors.taskAlreadyExists}:${task.name}`); + } + ctx.db.retryTask.insert({ + ...task, + scheduledId: 0n, + scheduledAt: ScheduleAt.time(ctx.timestamp.microsSinceUnixEpoch), + attempt: 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); + function dispatch(ctx: RetryCtx, args: TaskRow['args']): RetryResult { + if (!Object.prototype.hasOwnProperty.call(handlers, args.tag)) { + throw new Error(`${errors.unknownHandler}:${args.tag}`); } + const value = 'value' in args ? args.value : undefined; + return handlers[args.tag].run(ctx, value); + } + function retryFire(ctx: RetryCtx, { arg }: { arg: TaskRow }): void { let result: RetryResult; try { - result = dispatchRetry( - retryCtx, - arg.args as RetryDispatchArg & { tag: keyof H & string } - ); + result = dispatch(ctx, arg.args); } catch (error) { // A caught exception does not roll back the handler's earlier writes. result = retryFailed( @@ -206,146 +206,99 @@ export function createRetrySubmodule( ); } - 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, + const isLast = !result.ok && arg.attempt + 1 >= arg.maxAttempts; + const history = ctx.db.retryHistory; + history.insert({ + id: 0n, + taskName: arg.name, + attempt: arg.attempt, + status: { tag: result.ok ? 'Ok' : isLast ? 'GaveUp' : 'Failed' }, + error: result.ok ? undefined : result.error.slice(0, MAX_ERROR_LENGTH), + ranAt: ctx.timestamp, }); + // Each fire adds one row, so removing the oldest keeps the bound. + if (history.count() > MAX_ROWS) { + const oldest = history.ranAt.filter(new Range()).next().value; + if (oldest) history.delete(oldest); + } + if (result.ok || isLast) return; - if (isLast) return; - - const factor = 1n << BigInt(arg.attempt); - const delay = BigInt(arg.backoffSecs) * factor * ONE_SECOND_MICROS; - retryCtx.db.retryTask.insert({ + const delay = + BigInt(arg.backoffSecs) * (1n << BigInt(arg.attempt)) * ONE_SECOND_MICROS; + ctx.db.retryTask.insert({ ...arg, scheduledId: 0n, - scheduledAt: ScheduleAt.time(nowMicros + delay), + scheduledAt: ScheduleAt.time(ctx.timestamp.microsSinceUnixEpoch + 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, - }); - } + /** The latest pending tasks, newest first. */ + function retryTasksAdmin(ctx: RetryViewCtx): TaskRow[] { + if (!isAdmin(ctx)) return []; + return [...ctx.db.retryTask.iter()] + .sort((a, b) => + a.scheduledId > b.scheduledId + ? -1 + : a.scheduledId < b.scheduledId + ? 1 + : 0 + ) + .slice(0, MAX_ROWS); } - 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); + /** Retained attempt history, newest first. */ + function retryHistoryAdmin(ctx: RetryViewCtx): HistoryRow[] { + if (!isAdmin(ctx)) return []; + return [ + ...ctx.db.retryHistory.ranAt.filter(new Range()), + ].reverse(); } return { - tables: { - retryTask, - retryHistory, - retryAdminIdentity, - }, - retryArgs, - retryHistoryStatus, - RetryHistoryStatus, + tables: { retryTask, retryHistory, retryAdminIdentity }, install, - requireAdmin, - views: { - retryTasksAdmin, - retryHistoryAdmin, + /** Validate and schedule a task's first attempt. The caller authorizes. */ + submit( + ctx: RetryCtx, + task: Omit & { args: RetryArgs } + ): void { + submitTask(ctx, task); }, + requireAdmin, + views: { retryTasksAdmin, retryHistoryAdmin }, reducers: { retryFire, submitRetryTask: { - params: submitRetryTaskParams, - handler: submitRetryTask, + params: { + name: t.string(), + args: retryArgs, + maxAttempts: t.u8(), + backoffSecs: t.u32(), + }, + handler(ctx: RetryCtx, task: TaskInput): void { + requireAdmin(ctx); + submitTask(ctx, task); + }, }, addRetryAdminIdentity: { params: { identity: t.identity() }, - handler: addRetryAdminIdentity, + handler(ctx: RetryCtx, { identity }: { identity: Identity }): void { + requireAdmin(ctx); + addAdmin(ctx, identity); + }, }, removeRetryAdminIdentity: { params: { identity: t.identity() }, - handler: removeRetryAdminIdentity, + handler(ctx: RetryCtx, { identity }: { identity: Identity }): void { + requireAdmin(ctx); + const existing = ctx.db.retryAdminIdentity.identity.find(identity); + if (!existing) return; + if (ctx.db.retryAdminIdentity.count() <= 1n) { + throw new SenderError(errors.cannotRemoveLastAdmin); + } + ctx.db.retryAdminIdentity.delete(existing); + }, }, }, } as const; diff --git a/spacetime-retry-ts/tsconfig.json b/spacetime-retry-ts/tsconfig.json index b2b4ecdcdda..77da6c09f65 100644 --- a/spacetime-retry-ts/tsconfig.json +++ b/spacetime-retry-ts/tsconfig.json @@ -7,8 +7,7 @@ "noEmit": true, "skipLibCheck": true, "moduleResolution": "Bundler", - "isolatedModules": true, - "allowImportingTsExtensions": true + "isolatedModules": true }, "include": ["src/**/*.ts", "scripts/**/*.ts"], "exclude": ["node_modules"] From 8fd1b811a804b9a872cec63092b89eaa7c1cd020 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:31:37 -0400 Subject: [PATCH 12/32] Return failure reasons from webhook signature checks verifyStripeSignature, verifySvixSignature, and verifyGithubSignature return { ok: true } or { ok: false, reason } with a code from the exported errors object, so callers can tell a missing signature, a bad or stale timestamp, an invalid Svix secret, and a mismatch apart. Also remove the unused SHA256_INTERNAL_BLOCK_SIZE constant, make timingSafeEqual compile under noUncheckedIndexedAccess and enable that check, and drop allowImportingTsExtensions now that tests import without extensions. --- spacetime-crypto-ts/README.md | 17 +- spacetime-crypto-ts/scripts/test-vectors.ts | 189 +++++++++++--------- spacetime-crypto-ts/src/index.ts | 3 + spacetime-crypto-ts/src/sha256.ts | 1 - spacetime-crypto-ts/src/timing.ts | 2 +- spacetime-crypto-ts/src/vendors.ts | 104 +++++++---- spacetime-crypto-ts/tsconfig.json | 2 +- 7 files changed, 191 insertions(+), 127 deletions(-) diff --git a/spacetime-crypto-ts/README.md b/spacetime-crypto-ts/README.md index 64b2192ef28..ae5053ce01e 100644 --- a/spacetime-crypto-ts/README.md +++ b/spacetime-crypto-ts/README.md @@ -25,14 +25,18 @@ after signature verification succeeds. Verify a Stripe webhook with the raw body and module time: ```ts +import { SyncResponse } from 'spacetimedb/server'; import { verifyStripeSignature } from '@spacetimedb/crypto'; -const valid = verifyStripeSignature({ +const result = verifyStripeSignature({ rawBody, signatureHeader: request.headers.get('stripe-signature') ?? '', secret: webhookSecret, nowSeconds: Number(ctx.timestamp.microsSinceUnixEpoch / 1_000_000n), }); +if (!result.ok) { + return new SyncResponse(result.reason, { status: 400 }); +} ``` Verify the raw webhook body before parsing it. Store webhook secrets in private @@ -50,6 +54,17 @@ tables and keep them out of public rows and procedure results. Resend webhooks. - `verifyGithubSignature(options)` verifies GitHub's SHA-256 webhook signature. +The verifiers return `{ ok: true }` or `{ ok: false, reason }`. `reason` is one +of the `errors` codes, so the caller decides what to log or return: + +| Code | Meaning | +| ------------------------------------ | ------------------------------------------------------ | +| `crypto.missing_signature` | The header has no timestamp or no supported signature. | +| `crypto.invalid_timestamp` | The signed timestamp is not an integer. | +| `crypto.timestamp_outside_tolerance` | The timestamp is outside `toleranceSeconds`. | +| `crypto.invalid_secret` | The Svix secret is not valid base64. | +| `crypto.signature_mismatch` | No signature matches the body and secret. | + Package entrypoints: - `@spacetimedb/crypto` exports hashing, encoding, comparison, and vendor diff --git a/spacetime-crypto-ts/scripts/test-vectors.ts b/spacetime-crypto-ts/scripts/test-vectors.ts index d298d69e398..cac4ed1d834 100644 --- a/spacetime-crypto-ts/scripts/test-vectors.ts +++ b/spacetime-crypto-ts/scripts/test-vectors.ts @@ -5,19 +5,21 @@ // 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 { sha256 } from '../src/sha256'; +import { hmacSha256 } from '../src/hmac'; import { bytesToHex, hexToBytes, timingSafeEqual, base64ToBytes, -} from '../src/timing.ts'; +} from '../src/timing'; import { + errors, verifyStripeSignature, verifyGithubSignature, verifySvixSignature, -} from '../src/vendors.ts'; + type VerifyResult, +} from '../src/vendors'; const enc = new TextEncoder(); @@ -46,6 +48,20 @@ function assert(label: string, cond: boolean): void { } } +function assertResult( + label: string, + got: VerifyResult, + expected: VerifyResult +): void { + assertEq(label, JSON.stringify(got), JSON.stringify(expected)); +} + +const ok: VerifyResult = { ok: true }; +const fails = (reason: keyof typeof errors): VerifyResult => ({ + ok: false, + reason: errors[reason], +}); + // SHA-256 process.stdout.write('SHA-256\n'); assertEq( @@ -217,51 +233,52 @@ const stripeMac = hmacSha256( 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( +const stripe = { + rawBody: stripeBody, + signatureHeader: stripeHeader, + secret: stripeSecret, + toleranceSeconds: Infinity, +}; +assertResult('valid signature passes', verifyStripeSignature(stripe), ok); +assertResult( 'mutated body fails', - !verifyStripeSignature({ - rawBody: stripeBody + 'x', - signatureHeader: stripeHeader, - secret: stripeSecret, - toleranceSeconds: Infinity, - }) + verifyStripeSignature({ ...stripe, rawBody: stripeBody + 'x' }), + fails('signatureMismatch') ); -assert( +assertResult( 'wrong secret fails', - !verifyStripeSignature({ - rawBody: stripeBody, - signatureHeader: stripeHeader, - secret: 'whsec_wrong', - toleranceSeconds: Infinity, - }) + verifyStripeSignature({ ...stripe, secret: 'whsec_wrong' }), + fails('signatureMismatch') ); -assert( +assertResult( + 'missing v1 entry fails', + verifyStripeSignature({ ...stripe, signatureHeader: `t=${stripeTs}` }), + fails('missingSignature') +); +assertResult( + 'non-numeric timestamp fails', + verifyStripeSignature({ + ...stripe, + signatureHeader: `t=soon,v1=${bytesToHex(stripeMac)}`, + }), + fails('invalidTimestamp') +); +assertResult( 'old timestamp rejected when tolerance enforced', - !verifyStripeSignature({ - rawBody: stripeBody, - signatureHeader: stripeHeader, - secret: stripeSecret, + verifyStripeSignature({ + ...stripe, toleranceSeconds: 300, nowSeconds: Number(stripeTs) + 1000, - }) + }), + fails('timestampOutsideTolerance') ); -assert( +assertResult( 'multiple v1 entries: any match wins', verifyStripeSignature({ - rawBody: stripeBody, + ...stripe, signatureHeader: `t=${stripeTs},v1=deadbeef,v1=${bytesToHex(stripeMac)}`, - secret: stripeSecret, - toleranceSeconds: Infinity, - }) + }), + ok ); // GitHub signature round-trip @@ -269,13 +286,21 @@ 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, - }) +const github = { + rawBody: ghBody, + signatureHeader: `sha256=${bytesToHex(ghMac)}`, + secret: ghSecret, +}; +assertResult('roundtrip passes', verifyGithubSignature(github), ok); +assertResult( + 'missing prefix fails', + verifyGithubSignature({ ...github, signatureHeader: bytesToHex(ghMac) }), + fails('missingSignature') +); +assertResult( + 'wrong secret fails', + verifyGithubSignature({ ...github, secret: 'wrong' }), + fails('signatureMismatch') ); // Known vector from GitHub docs. assertEq( @@ -286,26 +311,8 @@ assertEq( // 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 svixSecretRaw = new Uint8Array(32).fill(0x42); +const toBase64 = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64'); const svixId = 'msg_test_123'; const svixTs = '1700000000'; const svixBody = '{"event":"email.delivered"}'; @@ -313,28 +320,38 @@ 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( +const svix = { + rawBody: svixBody, + svixId, + svixTimestamp: svixTs, + svixSignature: `v1,${toBase64(svixMac)}`, + secret: `whsec_${toBase64(svixSecretRaw)}`, + toleranceSeconds: Infinity, +}; +assertResult('valid svix signature passes', verifySvixSignature(svix), ok); +assertResult( 'mutated svix body fails', - !verifySvixSignature({ - rawBody: svixBody + 'x', - svixId, - svixTimestamp: svixTs, - svixSignature: svixSig, - secret: svixSecret, - toleranceSeconds: Infinity, - }) + verifySvixSignature({ ...svix, rawBody: svixBody + 'x' }), + fails('signatureMismatch') +); +assertResult( + 'invalid base64 secret fails', + verifySvixSignature({ ...svix, secret: 'whsec_not base64' }), + fails('invalidSecret') +); +assertResult( + 'no v1 signature fails', + verifySvixSignature({ ...svix, svixSignature: 'v2,abc' }), + fails('missingSignature') +); +assertResult( + 'old svix timestamp rejected', + verifySvixSignature({ + ...svix, + toleranceSeconds: 300, + nowSeconds: Number(svixTs) + 301, + }), + fails('timestampOutsideTolerance') ); // Summary diff --git a/spacetime-crypto-ts/src/index.ts b/spacetime-crypto-ts/src/index.ts index edc58185181..3f3c2b9a2e6 100644 --- a/spacetime-crypto-ts/src/index.ts +++ b/spacetime-crypto-ts/src/index.ts @@ -8,10 +8,13 @@ export { } from './timing'; export { + errors, verifyStripeSignature, verifySvixSignature, verifyGithubSignature, type StripeVerifyOpts, type SvixVerifyOpts, type GithubVerifyOpts, + type VerifyFailure, + type VerifyResult, } from './vendors'; diff --git a/spacetime-crypto-ts/src/sha256.ts b/spacetime-crypto-ts/src/sha256.ts index 6c248908d44..6b93c308010 100644 --- a/spacetime-crypto-ts/src/sha256.ts +++ b/spacetime-crypto-ts/src/sha256.ts @@ -5,4 +5,3 @@ export function sha256(data: Uint8Array): Uint8Array { } 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 index 8fa79ebfe24..ff1f671ba60 100644 --- a/spacetime-crypto-ts/src/timing.ts +++ b/spacetime-crypto-ts/src/timing.ts @@ -15,7 +15,7 @@ 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]; + diff |= a[i]! ^ b[i]!; } return diff === 0; } diff --git a/spacetime-crypto-ts/src/vendors.ts b/spacetime-crypto-ts/src/vendors.ts index 791e16e7b9b..3fdf867a1cb 100644 --- a/spacetime-crypto-ts/src/vendors.ts +++ b/spacetime-crypto-ts/src/vendors.ts @@ -8,6 +8,36 @@ import { timingSafeEqual, hexToBytes, base64ToBytes } from './timing'; const enc = new TextEncoder(); +/** Reasons a webhook signature check fails. */ +export const errors = { + missingSignature: 'crypto.missing_signature', + invalidTimestamp: 'crypto.invalid_timestamp', + timestampOutsideTolerance: 'crypto.timestamp_outside_tolerance', + invalidSecret: 'crypto.invalid_secret', + signatureMismatch: 'crypto.signature_mismatch', +} as const; + +export type VerifyFailure = (typeof errors)[keyof typeof errors]; + +export type VerifyResult = { ok: true } | { ok: false; reason: VerifyFailure }; + +const verified: VerifyResult = { ok: true }; +const failed = (reason: VerifyFailure): VerifyResult => ({ ok: false, reason }); + +function checkTimestamp( + value: string, + toleranceSeconds: number, + nowSeconds: number | undefined +): VerifyResult { + const t = Number.parseInt(value, 10); + if (!Number.isFinite(t)) return failed(errors.invalidTimestamp); + const now = nowSeconds ?? Math.floor(Date.now() / 1000); + if (toleranceSeconds !== Infinity && Math.abs(now - t) > toleranceSeconds) { + return failed(errors.timestampOutsideTolerance); + } + return verified; +} + // Stripe export interface StripeVerifyOpts { @@ -29,14 +59,11 @@ export interface StripeVerifyOpts { } /** - * Verify a Stripe webhook signature. Returns true iff the signature header - * contains at least one valid v1 signature AND the timestamp is within + * Verify a Stripe webhook signature. Succeeds when 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); - +export function verifyStripeSignature(opts: StripeVerifyOpts): VerifyResult { // Parse "t=1709836800,v1=abcdef,v1=12345..." into a map. // Multiple v1 entries are possible after key rotation; any match wins. const fields: Record = {}; @@ -50,11 +77,13 @@ export function verifyStripeSignature(opts: StripeVerifyOpts): boolean { 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; + if (!tStr || !v1List) return failed(errors.missingSignature); + const timestamp = checkTimestamp( + tStr, + opts.toleranceSeconds ?? 300, + opts.nowSeconds + ); + if (!timestamp.ok) return timestamp; const signed = enc.encode(`${tStr}.${opts.rawBody}`); const expected = hmacSha256(enc.encode(opts.secret), signed); @@ -66,9 +95,9 @@ export function verifyStripeSignature(opts: StripeVerifyOpts): boolean { } catch { continue; } - if (timingSafeEqual(expected, candidate)) return true; + if (timingSafeEqual(expected, candidate)) return verified; } - return false; + return failed(errors.signatureMismatch); } // Resend webhooks use Svix signatures. @@ -87,16 +116,14 @@ export interface SvixVerifyOpts { 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; +/** Verify a Svix webhook signature, as sent by Resend, Clerk, and others. */ +export function verifySvixSignature(opts: SvixVerifyOpts): VerifyResult { + const timestamp = checkTimestamp( + opts.svixTimestamp, + opts.toleranceSeconds ?? 300, + opts.nowSeconds + ); + if (!timestamp.ok) return timestamp; // Strip the `whsec_` prefix, base64-decode the rest. const secretBody = opts.secret.startsWith('whsec_') @@ -106,7 +133,7 @@ export function verifySvixSignature(opts: SvixVerifyOpts): boolean { try { secretBytes = base64ToBytes(secretBody); } catch { - return false; + return failed(errors.invalidSecret); } const signed = enc.encode( @@ -115,21 +142,20 @@ export function verifySvixSignature(opts: SvixVerifyOpts): boolean { 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); + const signatures = opts.svixSignature + .split(' ') + .filter(part => part.startsWith('v1,')); + if (signatures.length === 0) return failed(errors.missingSignature); + for (const part of signatures) { let candidate: Uint8Array; try { - candidate = base64ToBytes(sigB64); + candidate = base64ToBytes(part.slice('v1,'.length)); } catch { continue; } - if (timingSafeEqual(expected, candidate)) return true; + if (timingSafeEqual(expected, candidate)) return verified; } - return false; + return failed(errors.signatureMismatch); } // GitHub @@ -143,18 +169,22 @@ export interface GithubVerifyOpts { } /** Verify a GitHub webhook signature (HMAC-SHA256 of body, hex-encoded). */ -export function verifyGithubSignature(opts: GithubVerifyOpts): boolean { +export function verifyGithubSignature(opts: GithubVerifyOpts): VerifyResult { const prefix = 'sha256='; - if (!opts.signatureHeader.startsWith(prefix)) return false; + if (!opts.signatureHeader.startsWith(prefix)) { + return failed(errors.missingSignature); + } let candidate: Uint8Array; try { candidate = hexToBytes(opts.signatureHeader.slice(prefix.length)); } catch { - return false; + return failed(errors.signatureMismatch); } const expected = hmacSha256( enc.encode(opts.secret), enc.encode(opts.rawBody) ); - return timingSafeEqual(expected, candidate); + return timingSafeEqual(expected, candidate) + ? verified + : failed(errors.signatureMismatch); } diff --git a/spacetime-crypto-ts/tsconfig.json b/spacetime-crypto-ts/tsconfig.json index e6a8236bbab..8d86936bedc 100644 --- a/spacetime-crypto-ts/tsconfig.json +++ b/spacetime-crypto-ts/tsconfig.json @@ -7,7 +7,7 @@ "noEmit": true, "skipLibCheck": true, "resolveJsonModule": true, - "allowImportingTsExtensions": true, + "noUncheckedIndexedAccess": true, "isolatedModules": true }, "include": ["src/**/*.ts", "scripts/**/*.ts"] From b47fe599091576e129e9ef8b59557c8f7a36671a Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:43:18 -0400 Subject: [PATCH 13/32] Keep rate-limit policy in the limiter client Limiters are configured once per scope and expose their policy and a peek read. Remove per-call limit overrides, the admin consume procedure, and the raw consume and key exports. Export isAdmin and requireAdmin for host operations. The example uses one limiter per upgrade tier, reads status through peek, and uses reactor.* codes for its own errors. Regenerate example bindings. --- spacetime-rate-limit-ts/README.md | 97 +++--- spacetime-rate-limit-ts/example/README.md | 19 +- .../example/scripts/test-reactor-rules.ts | 8 + .../example/spacetimedb/src/index.ts | 234 ++++++-------- .../example/spacetimedb/src/reactor-rules.ts | 15 + .../example/src/module_bindings/app/index.ts | 29 +- .../app/rateLimit/consume_procedure.ts | 24 -- .../module_bindings/app/rateLimit/types.ts | 12 - spacetime-rate-limit-ts/scripts/test.ts | 178 ++++------- .../spacetimedb/src/index.ts | 1 - spacetime-rate-limit-ts/src/index.ts | 6 +- spacetime-rate-limit-ts/src/key.ts | 7 - spacetime-rate-limit-ts/src/limit.ts | 296 +++++++++--------- spacetime-rate-limit-ts/src/submodule.ts | 9 +- .../src/submodule/operations.ts | 92 +----- 15 files changed, 413 insertions(+), 614 deletions(-) delete mode 100644 spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/consume_procedure.ts delete mode 100644 spacetime-rate-limit-ts/src/key.ts diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index 2a224d5d396..f1ecf866fe4 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -14,16 +14,16 @@ For the install-to-publish workflow, see 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 +- configured limiter clients that consume and read buckets in host transactions +- a scheduled, bounded sweep of expired buckets +- admin-gated operations 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: +Register the namespace, install its scheduled cleanup and admin state, then +consume from a limiter before performing the protected action: ```ts import { schema, SenderError, t, table } from 'spacetimedb/server'; @@ -51,7 +51,7 @@ export const init = spacetimedb.init(ctx => { export default spacetimedb; ``` -Host procedures should call the standalone policy helper inside the same +Configure each policy once at module scope, then consume inside the same transaction as the protected write. Derive the actor key from trusted request or session state: @@ -69,7 +69,7 @@ export const createPost = spacetimedb.procedure( ctx.withTx(tx => { const actor = ctx.sender.toHexString(); const result = postLimiter.consume(tx.as.rateLimit, { key: actor }); - if (!result.allowed) throw new SenderError('rate_limit.blocked'); + if (!result.allowed) throw new SenderError('post.rate_limited'); const body = args.body.trim(); if (!body) throw new SenderError('post.empty'); tx.db.post.insert({ @@ -90,55 +90,80 @@ The generated client calls the product-facing operation: await conn.procedures.createPost({ body: 'Hello' }); ``` -The submodule owns these tables under its namespace: +A view can report the caller's remaining capacity with `peek`: -- `rateLimit.rate_limit_bucket` -- `rateLimit.rate_limit_admin_identity` -- `rateLimit.rate_limit_config` -- `rateLimit.rate_limit_sweep_tick` +```ts +export const postLimitStatus = spacetimedb.view( + { name: 'post_limit_status', public: true }, + t.array( + t.object('PostLimitStatus', { + limit: t.u32(), + windowSeconds: t.u32(), + used: t.u32(), + remaining: t.u32(), + resetAt: t.option(t.timestamp()), + }) + ), + ctx => [postLimiter.peek(ctx.db.rateLimit, ctx.sender.toHexString())] +); +``` -It also exposes the public admin view `rateLimit.admin_rate_limit_buckets`. +Mounted as `rateLimit`, the submodule owns these tables: + +- `rate_limit.rate_limit_bucket` +- `rate_limit.rate_limit_admin_identity` +- `rate_limit.rate_limit_config` +- `rate_limit.rate_limit_sweep_tick` + +It also exposes the public admin view `rate_limit.admin_rate_limit_buckets`. The view returns at most 1,000 rows and returns an empty set to non-admins. ## API -Configure a policy once with `client({ scope, limit, windowSeconds })`. Call -`limiter.consume(ctx, { key, cost?, limit?, windowSeconds? })` in the caller's -transaction. `key` identifies the actor; the library combines it with the scope. -Override limits or windows only for application-owned dynamic policies. +`client({ scope, limit, windowSeconds })` configures the policy for one scope. +Each scope can be configured once per module; a second `client` call with the +same scope throws `errors.duplicateScope`. When a policy depends on application +state, such as an upgrade tier, create one client per tier with its own scope. +The returned limiter exposes `scope`, `limit`, and `windowSeconds`, plus: + +- `consume(ctx, { key, cost? })` spends `cost` (default 1) from the actor's + bucket in the caller's transaction and returns whether it was allowed, the + remaining capacity, the reset time, and the retry delay. +- `peek(db, key, now?)` reads the actor's bucket without spending from it. + Views have no clock, so a view reports an expired window until the sweep + removes it; compare `resetAt` with the current time, or pass `now` from a + reducer or procedure to report an expired window as fresh. + +`key` identifies the actor; the limiter combines it with the scope. Scopes are +at most 128 characters and keys at most 256. `install(ctx)` makes the publishing identity the first administrator and schedules a sweep of expired buckets every 30 seconds. Call it from the host's `init` reducer. Repeated installation does not add administrators or timers. -Admins can grant and revoke access with `addRateLimitAdmin` and -`removeRateLimitAdmin`. The last administrator cannot be removed. - -`errors` exports stable error codes for callers that distinguish failures. -The root package also exports lower-level helpers for standalone integrations: +Admin operations: -- `consumeRateLimit` -- `buildRateLimitKey` +- `isAdmin(db, identity)` and `requireAdmin(ctx)` check the submodule's admin + table for host operations that share its administrators. +- `addRateLimitAdmin` and `removeRateLimitAdmin` grant and revoke access. The + last administrator cannot be removed. +- `updateConfig({ sweepBatch })` sets how many expired rows each scheduled sweep + deletes: 500 by default, at most 10,000. +- `runSweep({ maxRows })` deletes expired buckets now, and + `resetBuckets({ maxRows })` deletes buckets regardless of expiry. Both remove + 500 rows by default and accept at most 10,000 per call. -The submodule `consume`, `runSweep`, and `resetBuckets` operations are admin-only. -Application-facing operations should enforce a fixed policy in host code and use -the configured limiter shown above. `runSweep({ maxRows })` and -`resetBuckets({ maxRows })` remove 500 rows by default and accept at most 10,000 -per call. `updateConfig({ sweepBatch })` sets how many expired rows each -scheduled sweep deletes, with the same default and maximum. +`errors` exports stable error codes for callers that distinguish failures. Package entrypoints: - `@spacetimedb/rate-limit/submodule` supplies the submodule namespace, - maintenance operations, and host helpers. -- `@spacetimedb/rate-limit` re-exports the supported helper surface. + `install`, the limiter client, and the admin operations. +- `@spacetimedb/rate-limit` exports `client`, `errors`, and their types. See the [Powerhouse host module](./example/spacetimedb/) -for per-action policies, caller-visible status, and admin controls. - -Use `buildRateLimitKey(scope, actorKey)` only when reading an existing bucket for -a status view. Consuming a configured policy does not require constructing keys. +for per-action and per-tier policies, caller-visible status, and admin controls. ## Testing diff --git a/spacetime-rate-limit-ts/example/README.md b/spacetime-rate-limit-ts/example/README.md index 7f06ad0eb22..e28e0e71e8c 100644 --- a/spacetime-rate-limit-ts/example/README.md +++ b/spacetime-rate-limit-ts/example/README.md @@ -80,12 +80,17 @@ The Node process serves static files, `GET /api/health`, and browser-safe ## 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. +Each protected action has a limiter configured once with +`rateLimit.client({ scope, limit, windowSeconds })`. The host procedure calls +`limiter.consume(tx.as.rateLimit, { key })` inside its transaction with an actor +key derived from `ctx.sender`. The returned result includes remaining capacity, +reset time, and retry delay. The `reactor_limit_status` view reads the same +limiters with `limiter.peek(ctx.db.rateLimit, key)`. + +Tap Batteries and Upgrade Bay levels change the tap limit and the shop window. +Each level has its own limiter and scope (`reactor.tap.0`, `reactor.tap.1`, and so +on), so buying a level starts a fresh bucket. Those lanes are capped at the last +level that has a limiter. The submodule implements fixed-window limiting. Application heat and cooldown mechanics are separate game rules layered over the rate limit, so a request may @@ -115,7 +120,7 @@ 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 +spacetime call --server local spacetime-rate-limit-example rate_limit.add_rate_limit_admin 0x ``` Admin resets and sweeps are bounded. Do not turn an unbounded delete into an diff --git a/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts b/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts index 5da0ad814e9..4c97f60d734 100644 --- a/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts +++ b/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts @@ -1,11 +1,13 @@ import * as assert from 'node:assert/strict'; import { COOLANT_UNLOCK_LEVEL, + MAX_BAY_LEVEL, SURGE_UNLOCK_LEVEL, hasCoolantFlush, hasSurgeBurst, roomTuning, tapLimitForState, + upgradeAvailable, upgradeOffer, upgradeWindowForState, type UpgradeState, @@ -32,6 +34,12 @@ assert.deepEqual(roomTuning(state, 3), { assert.equal(upgradeOffer(state, 'power').cost, 12n); assert.equal(tapLimitForState({ chargeUpgradeCount: 2 }), 12); assert.equal(upgradeWindowForState({ bayUpgradeCount: 99 }), 5); +assert.equal(upgradeWindowForState({ bayUpgradeCount: MAX_BAY_LEVEL }), 5); +assert.equal( + upgradeAvailable({ ...state, bayUpgradeCount: MAX_BAY_LEVEL }, 'bay'), + false +); +assert.equal(upgradeAvailable(state, 'charges'), true); assert.equal( hasCoolantFlush({ coolingUpgradeCount: COOLANT_UNLOCK_LEVEL }), true diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts index 333a5dc2edc..7aa70cfd79c 100644 --- a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts @@ -1,12 +1,13 @@ -import { t, Range, SenderError, type ViewCtx } from 'spacetimedb/server'; +import { t, Range, SenderError } from 'spacetimedb/server'; import * as rateLimit from '@spacetimedb/rate-limit/submodule'; import { ScheduleAt, Timestamp } from 'spacetimedb'; import { COOLANT_UNLOCK_LEVEL, + MAX_BAY_LEVEL, + MAX_CHARGE_LEVEL, PLAYER_COLORS, POWER_PER_UPGRADE, SURGE_UNLOCK_LEVEL, - TAP_LIMIT, hasCoolantFlush, hasSurgeBurst, overheatRecoverAt, @@ -14,10 +15,19 @@ import { playerName, roomTuning, tapLimitForState, + upgradeAvailable, upgradeOffer, upgradeWindowForState, type UpgradeLane, } from './reactor-rules'; +import { + rateLimitEvent, + reactorEvent, + reactorRoomState, + rateLimitDemoSweepTick, + spacetimedb, + type Tx, +} from './schema'; const ONE_SECOND_MICROS = 1_000_000n; @@ -34,27 +44,43 @@ const UPGRADE_LIMIT = 2; const REPAIR_LIMIT = 1; const REPAIR_WINDOW_SECONDS = 18; -const tapLimiter = rateLimit.client({ - scope: TAP_SCOPE, - limit: TAP_LIMIT, - windowSeconds: TAP_WINDOW_SECONDS, -}); +// Tap Batteries and Upgrade Bay levels change a policy, so each level has its +// own limiter and scope. Buying a level starts a fresh bucket. +const tapLimiters = Array.from({ length: MAX_CHARGE_LEVEL + 1 }, (_, level) => + rateLimit.client({ + scope: `${TAP_SCOPE}.${level}`, + limit: tapLimitForState({ chargeUpgradeCount: level }), + windowSeconds: TAP_WINDOW_SECONDS, + }) +); const overchargeLimiter = rateLimit.client({ scope: OVERCHARGE_SCOPE, limit: OVERCHARGE_LIMIT, windowSeconds: OVERCHARGE_WINDOW_SECONDS, }); -const upgradeLimiter = rateLimit.client({ - scope: UPGRADE_SCOPE, - limit: UPGRADE_LIMIT, - windowSeconds: upgradeWindowForState(null), -}); +const upgradeLimiters = Array.from({ length: MAX_BAY_LEVEL + 1 }, (_, level) => + rateLimit.client({ + scope: `${UPGRADE_SCOPE}.${level}`, + limit: UPGRADE_LIMIT, + windowSeconds: upgradeWindowForState({ bayUpgradeCount: level }), + }) +); const repairLimiter = rateLimit.client({ scope: REPAIR_SCOPE, limit: REPAIR_LIMIT, windowSeconds: REPAIR_WINDOW_SECONDS, }); +function tapLimiter(state: { chargeUpgradeCount: number } | null) { + return tapLimiters[ + Math.min(state?.chargeUpgradeCount ?? 0, MAX_CHARGE_LEVEL) + ]; +} + +function upgradeLimiter(state: { bayUpgradeCount: number } | null) { + return upgradeLimiters[Math.min(state?.bayUpgradeCount ?? 0, MAX_BAY_LEVEL)]; +} + const DEFAULT_RETAIN_EVENTS = 2000; const DEFAULT_EVENT_PRUNE_BATCH = 500; const DEFAULT_RETAIN_REACTOR_EVENTS = 80; @@ -62,15 +88,6 @@ 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< @@ -132,35 +149,10 @@ const reactorActionResult = t.object('ReactorActionResult', { 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))); } @@ -337,40 +329,28 @@ function pruneReactorEvents(tx: Tx): void { 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}`); - } +function requirePositive(code: string, value: number): number { + if (value <= 0) throw new SenderError(code); 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']; - } + limiter: rateLimit.RateLimitClient, + result: rateLimit.RateLimitResult ) { 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, + scope: result.scope, + key: result.key, + allowed: result.allowed, + limit: result.limit, + used: result.used, + remaining: result.remaining, + retryAfterSeconds: result.retryAfterSeconds, + windowSeconds: limiter.windowSeconds, + cost: 1, + resetAt: result.resetAt, createdAt: tx.timestamp, }); } @@ -470,47 +450,30 @@ export const reactorLimitStatus = spacetimedb.view( 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 = [ + const db = ctx.db.rateLimit; + const actor = actorKey(ctx); + return [ { scope: TAP_SCOPE, label: 'Tap Coils', - limit: tapLimit, - windowSeconds: TAP_WINDOW_SECONDS, + ...tapLimiter(state).peek(db, actor), }, { scope: OVERCHARGE_SCOPE, label: 'Overcharger', - limit: OVERCHARGE_LIMIT, - windowSeconds: OVERCHARGE_WINDOW_SECONDS, + ...overchargeLimiter.peek(db, actor), }, { scope: UPGRADE_SCOPE, label: 'Upgrade Bay', - limit: UPGRADE_LIMIT, - windowSeconds: upgradeWindowSeconds, + ...upgradeLimiter(state).peek(db, SHARED_REACTOR_KEY), }, { scope: REPAIR_SCOPE, label: 'Repair Drones', - limit: REPAIR_LIMIT, - windowSeconds: REPAIR_WINDOW_SECONDS, + ...repairLimiter.peek(db, actor), }, ]; - 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, - }; - }); } ); @@ -536,7 +499,7 @@ export const reactorShop = spacetimedb.view( description: offer.description, effect: offer.effect, cost: offer.cost, - available: true, + available: upgradeAvailable(base, lane), }; } ); @@ -547,7 +510,7 @@ export const rateLimitEventsAdmin = spacetimedb.view( { name: 'rate_limit_events_admin', public: true }, t.array(rateLimitEvent.rowType), ctx => - isAdmin(ctx) + rateLimit.isAdmin(ctx.db.rateLimit, ctx.sender) ? takeRows(ctx.db.rateLimitEvent.iter(), ADMIN_EVENT_VIEW_LIMIT) : [] ); @@ -573,17 +536,9 @@ export const tapReactor = spacetimedb.procedure( const key = actorKey(ctx); let out: ReturnType | null = null; ctx.withTx(tx => { - const tapLimit = tapLimitForState(currentState(tx)); - const result = tapLimiter.consume(tx.as.rateLimit, { - key, - limit: tapLimit, - }); - recordLimitHit(tx, { - ...result, - limit: tapLimit, - windowSeconds: TAP_WINDOW_SECONDS, - cost: 1, - }); + const limiter = tapLimiter(currentState(tx)); + const result = limiter.consume(tx.as.rateLimit, { key }); + recordLimitHit(tx, limiter, result); const state = currentState(tx); if (!result.allowed) { const next = putState(tx, { @@ -715,11 +670,7 @@ export const overcharge = spacetimedb.procedure( let out: ReturnType | null = null; ctx.withTx(tx => { const result = overchargeLimiter.consume(tx.as.rateLimit, { key }); - recordLimitHit(tx, { - ...result, - windowSeconds: OVERCHARGE_WINDOW_SECONDS, - cost: 1, - }); + recordLimitHit(tx, overchargeLimiter, result); const state = currentState(tx); if (!result.allowed || state.overheated) { const message = result.allowed @@ -799,22 +750,17 @@ export const buyUpgrade = spacetimedb.procedure( 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 = upgradeLimiter.consume(tx.as.rateLimit, { - key, - windowSeconds: upgradeWindowSeconds, - }); - recordLimitHit(tx, { - ...result, - windowSeconds: upgradeWindowSeconds, - cost: 1, - }); const state = currentState(tx); + if (!upgradeAvailable(state, lane)) { + throw new SenderError('reactor.upgrade_maxed'); + } + const limiter = upgradeLimiter(state); + const result = limiter.consume(tx.as.rateLimit, { + key: SHARED_REACTOR_KEY, + }); + recordLimitHit(tx, limiter, result); const offer = upgradeOffer(state, lane); const cost = offer.cost; if (!result.allowed) { @@ -962,11 +908,7 @@ export const repairReactor = spacetimedb.procedure( let out: ReturnType | null = null; ctx.withTx(tx => { const result = repairLimiter.consume(tx.as.rateLimit, { key }); - recordLimitHit(tx, { - ...result, - windowSeconds: REPAIR_WINDOW_SECONDS, - cost: 1, - }); + recordLimitHit(tx, repairLimiter, result); const state = currentState(tx); if (!result.allowed) { const message = `Coolant system cooling down for ${result.retryAfterSeconds}s.`; @@ -1029,11 +971,9 @@ 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 }); + const deleted = rateLimit.runSweep(ctx.as.rateLimit, { + maxRows: args.maxRows, + }); ctx.withTx(tx => { const demo = tx.db.rateLimitDemoConfig.singleton.find(true); const retainEvents = Number(demo?.retainEvents ?? DEFAULT_RETAIN_EVENTS); @@ -1059,7 +999,7 @@ export const setPlayerColor = spacetimedb.reducer( ); export const resetDemo = spacetimedb.reducer({}, ctx => { - requireAdmin(ctx); + rateLimit.requireAdmin(ctx.as.rateLimit); rateLimit.resetBuckets(ctx.as.rateLimit, {}); for (const row of ctx.db.rateLimitEvent.iter()) ctx.db.rateLimitEvent.delete(row); @@ -1077,25 +1017,29 @@ export const updateConfig = spacetimedb.reducer( eventPruneBatch: t.option(t.u32()), }, (ctx, args) => { - requireAdmin(ctx); + rateLimit.requireAdmin(ctx.as.rateLimit); if (args.sweepBatch !== undefined) { - rateLimit.updateConfig(ctx.as.rateLimit, { - sweepBatch: toU32('sweep_batch', Number(args.sweepBatch)), - }); + rateLimit.updateConfig(ctx.as.rateLimit, { sweepBatch: 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'); + if (!demo) throw new Error('reactor.demo_config_missing'); ctx.db.rateLimitDemoConfig.singleton.update({ ...demo, retainEvents: args.retainEvents === undefined ? demo.retainEvents - : toU32('retain_events', Number(args.retainEvents)), + : requirePositive( + 'reactor.invalid_retain_events', + args.retainEvents + ), eventPruneBatch: args.eventPruneBatch === undefined ? demo.eventPruneBatch - : toU32('event_prune_batch', Number(args.eventPruneBatch)), + : requirePositive( + 'reactor.invalid_event_prune_batch', + args.eventPruneBatch + ), updatedAt: ctx.timestamp, }); } diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts index 5288a4ae8bc..d7ebe38ec27 100644 --- a/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts @@ -25,6 +25,11 @@ const CAPACITY_PER_UPGRADE = 30; const CHARGES_PER_UPGRADE = 2; const UPGRADE_WINDOW_REDUCTION_SECONDS = 3; const MIN_UPGRADE_WINDOW_SECONDS = 5; +// Each level of these lanes has its own rate-limit policy, so they are capped. +export const MAX_CHARGE_LEVEL = 5; +export const MAX_BAY_LEVEL = + (UPGRADE_WINDOW_SECONDS - MIN_UPGRADE_WINDOW_SECONDS) / + UPGRADE_WINDOW_REDUCTION_SECONDS; export const PLAYER_COLORS = [ '#22c7b8', @@ -91,6 +96,16 @@ export function upgradeWindowForState( ); } +export function upgradeAvailable( + state: UpgradeState, + lane: UpgradeLane +): boolean { + const level = upgradeLevel(state, lane); + if (lane === 'charges') return level < MAX_CHARGE_LEVEL; + if (lane === 'bay') return level < MAX_BAY_LEVEL; + return true; +} + export function upgradeOffer( state: UpgradeState, lane: UpgradeLane 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 index ae22c4b9d58..e027d9f8555 100644 --- a/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts @@ -1,7 +1,7 @@ // 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). +// This was generated using spacetimedb cli version 2.11.0 (commit 094df0ed2107fe3a359f5e4ee7a4c344802fc96c). /* eslint-disable */ /* tslint:disable */ @@ -66,7 +66,6 @@ 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. */ @@ -126,8 +125,8 @@ const tablesSchema = __schema({ constraints: [ ], }, ReactorStateRow), - "rateLimit.rate_limit_config": __table({ - name: 'rateLimit.rate_limit_config', + "rate_limit.rate_limit_config": __table({ + name: 'rate_limit.rate_limit_config', indexes: [ { accessor: 'singleton', name: 'rate_limit_config_singleton_idx_btree', algorithm: 'btree', columns: [ 'singleton', @@ -137,8 +136,8 @@ const tablesSchema = __schema({ { name: 'rate_limit_config_singleton_key', constraint: 'unique', columns: ['singleton'] }, ], }, RateLimit_RateLimitConfigRow), - "rateLimit.admin_rate_limit_buckets": __table({ - name: 'rateLimit.admin_rate_limit_buckets', + "rate_limit.admin_rate_limit_buckets": __table({ + name: 'rate_limit.admin_rate_limit_buckets', indexes: [ ], constraints: [ @@ -151,10 +150,10 @@ 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.remove_rate_limit_admin", RateLimit_RemoveRateLimitAdminReducer), - __reducerSchema("rateLimit.reset_buckets", RateLimit_ResetBucketsReducer), - __reducerSchema("rateLimit.update_config", RateLimit_UpdateConfigReducer), + __reducerSchema("rate_limit.add_rate_limit_admin", RateLimit_AddRateLimitAdminReducer, "rateLimit.addRateLimitAdmin"), + __reducerSchema("rate_limit.remove_rate_limit_admin", RateLimit_RemoveRateLimitAdminReducer, "rateLimit.removeRateLimitAdmin"), + __reducerSchema("rate_limit.reset_buckets", RateLimit_ResetBucketsReducer, "rateLimit.resetBuckets"), + __reducerSchema("rate_limit.update_config", RateLimit_UpdateConfigReducer, "rateLimit.updateConfig"), ); /** 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. */ @@ -165,14 +164,13 @@ const proceduresSchema = __procedures( __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), + __procedureSchema("rate_limit.run_sweep", RateLimit_RunSweepProcedure.params, RateLimit_RunSweepProcedure.returnType, "rateLimit.runSweep"), ); /** The remote SpacetimeDB module schema, both runtime and type information. */ const REMOTE_MODULE = { versionInfo: { - cliVersion: "2.10.1" as const, + cliVersion: "2.11.0" as const, }, tables: tablesSchema.schemaType.tables, reducers: reducersSchema.reducersType.reducers, @@ -194,8 +192,8 @@ export const tables = { reactorShop: __qb.reactorShop, reactorState: __qb.reactorState, rateLimit: { - rateLimitConfig: __qb["rateLimit.rate_limit_config"], - adminRateLimitBuckets: __qb["rateLimit.admin_rate_limit_buckets"], + rateLimitConfig: __qb["rate_limit.rate_limit_config"], + adminRateLimitBuckets: __qb["rate_limit.admin_rate_limit_buckets"], }, } as const; @@ -223,7 +221,6 @@ export const procedures = { startReactor: __procedureAccessors.startReactor, tapReactor: __procedureAccessors.tapReactor, rateLimit: { - consume: __procedureAccessors["rateLimit.consume"], runSweep: __procedureAccessors["rateLimit.runSweep"], }, } as const; 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 deleted file mode 100644 index a98b8588aad..00000000000 --- a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/consume_procedure.ts +++ /dev/null @@ -1,24 +0,0 @@ -// 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/types.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts index dc6aa78cab2..d14931b1fb9 100644 --- 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 @@ -36,18 +36,6 @@ export const RateLimitConfig = __t.object("RateLimitConfig", { }); 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(), diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts index daa20953de1..ba8a1eca2b9 100644 --- a/spacetime-rate-limit-ts/scripts/test.ts +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -1,12 +1,11 @@ import { Timestamp } from 'spacetimedb'; import { - consumeRateLimit, client, + errors, MAX_SWEEP_BATCH, sweepRateLimits, type RateLimitBucketRow, } from '../src/limit.ts'; -import { buildRateLimitKey } from '../src/key.ts'; let pass = 0; let fail = 0; @@ -44,16 +43,6 @@ function makeTx(nowMicros = 0n) { }, 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, @@ -61,34 +50,10 @@ function makeTx(nowMicros = 0n) { 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 +function byExpiry(rows: Map) { + return [...rows.values()].sort((a, b) => + a.expiresAt.microsSinceUnixEpoch < b.expiresAt.microsSinceUnixEpoch ? -1 : 1 ); - 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'); @@ -97,14 +62,8 @@ process.stdout.write('\nrate limiter\n'); const tx = makeTx(); const tap = client({ scope: 'tap', windowSeconds: 60, limit: 1 }); const other = client({ scope: 'other', windowSeconds: 60, limit: 1 }); - assert( - tap.consume(tx, { key: 'alice' }).allowed, - 'configured policy allows first call' - ); - assert( - !tap.consume(tx, { key: 'alice' }).allowed, - 'configured policy enforces limit' - ); + assert(tap.consume(tx, { key: 'alice' }).allowed, 'first call allowed'); + assert(!tap.consume(tx, { key: 'alice' }).allowed, 'limit enforced'); assert( other.consume(tx, { key: 'alice' }).allowed, 'scopes have independent buckets' @@ -113,104 +72,77 @@ process.stdout.write('\nrate limiter\n'); tap.consume(tx, { key: 'bob' }).allowed, 'actors have independent buckets' ); - assert( - tap.consume(tx, { key: 'alice', limit: 2 }).allowed, - 'dynamic limit is supported' - ); -} - -{ - const tx = makeTx(); - consumeRateLimit(tx, { - key: 'fresh', - scope: 's', - limit: 1, - windowSeconds: 100, - }); - consumeRateLimit(tx, { - key: 'expired', - scope: 's', - limit: 1, - windowSeconds: 1, - }); - tx.timestamp = new Timestamp(2_000_000n); - assert( - sweepRateLimits(tx, tx.rows.values()) === 1, - 'sweep accepts unordered rows' + assertThrows( + () => client({ scope: 'tap', windowSeconds: 30, limit: 5 }), + errors.duplicateScope, + 'a scope can be configured once' ); -} - -{ - const tx = makeTx(); assertThrows( - () => sweepRateLimits(tx, [], MAX_SWEEP_BATCH + 1), - 'rate_limit.invalid_sweep_batch', - 'sweep rejects an excessive batch size' + () => tap.consume(tx, { key: '' }), + errors.invalidActorKey, + 'empty actor key rejected' ); } -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, - }); + const login = client({ scope: 'auth.login', limit: 2, windowSeconds: 60 }); + const one = login.consume(tx, { key: 'ip:1' }); + const two = login.consume(tx, { key: 'ip:1' }); + const three = login.consume(tx, { key: 'ip:1' }); 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 status = login.peek(tx.db, 'ip:1', tx.timestamp); + assert( + status.used === 2 && status.remaining === 0 && status.limit === 2, + 'peek reports the open window' + ); + assert( + login.peek(tx.db, 'ip:2').used === 0, + 'peek reports an unused bucket as fresh' + ); + tx.timestamp = new Timestamp(61_000_000n); + const expired = login.peek(tx.db, 'ip:1', tx.timestamp); + assert( + expired.used === 0 && expired.resetAt === undefined, + 'peek reports an expired window as fresh' + ); + const next = login.consume(tx, { key: 'ip:1' }); + assert(next.allowed && next.used === 1, 'expired window resets'); } { 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 a = client({ scope: 'a:actor:b', limit: 1, windowSeconds: 1 }); + const b = client({ scope: 'a', limit: 1, windowSeconds: 1 }); + assert( + a.consume(tx, { key: 'c' }).key !== b.consume(tx, { key: 'b:actor:c' }).key, + 'compound keys cannot collide through delimiters' + ); } { const tx = makeTx(); - consumeRateLimit(tx, { - key: 'k', - scope: 's', - limit: 1, - windowSeconds: 1, - }); + const long = client({ scope: 'sweep.long', limit: 1, windowSeconds: 100 }); + const short = client({ scope: 'sweep.short', limit: 1, windowSeconds: 1 }); + long.consume(tx, { key: 'a' }); + long.consume(tx, { key: 'b' }); + const expiredKey = short.consume(tx, { key: 'a' }).key; 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'); + assert( + sweepRateLimits(tx, byExpiry(tx.rows), 2) === 1, + 'sweep removes only expired buckets' + ); + assert(!tx.rows.has(expiredKey), 'sweep removes the expired bucket'); + assertThrows( + () => sweepRateLimits(tx, [], MAX_SWEEP_BATCH + 1), + errors.invalidSweepBatch, + 'sweep rejects an excessive batch size' + ); } process.stdout.write(`\n${pass} passed, ${fail} failed\n`); diff --git a/spacetime-rate-limit-ts/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/spacetimedb/src/index.ts index a0cdf415dac..af68ebad0f9 100644 --- a/spacetime-rate-limit-ts/spacetimedb/src/index.ts +++ b/spacetime-rate-limit-ts/spacetimedb/src/index.ts @@ -4,7 +4,6 @@ export { adminRateLimitBuckets, addRateLimitAdmin, removeRateLimitAdmin, - consume, rateLimitSweep, resetBuckets, runSweep, diff --git a/spacetime-rate-limit-ts/src/index.ts b/spacetime-rate-limit-ts/src/index.ts index 0e5119df8bf..8e0561d77b6 100644 --- a/spacetime-rate-limit-ts/src/index.ts +++ b/spacetime-rate-limit-ts/src/index.ts @@ -1,10 +1,10 @@ export { client, errors, - consumeRateLimit, - type ConsumeRateLimitOpts, + type RateLimitClient, type RateLimitPolicy, + type RateLimitReadDb, type RateLimitResult, + type RateLimitStatus, 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 deleted file mode 100644 index 7eb4c4b3cd4..00000000000 --- a/spacetime-rate-limit-ts/src/key.ts +++ /dev/null @@ -1,7 +0,0 @@ -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 index ccf3db0bf8f..0fd0710d9a5 100644 --- a/spacetime-rate-limit-ts/src/limit.ts +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -1,16 +1,18 @@ import { Timestamp } from 'spacetimedb'; -import { buildRateLimitKey } from './key'; 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; +const MAX_SCOPE_LENGTH = 128; +const MAX_ACTOR_KEY_LENGTH = 256; export const errors = { notAuthorized: 'rate_limit.not_authorized', cannotRemoveLastAdmin: 'rate_limit.cannot_remove_last_admin', invalidScope: 'rate_limit.invalid_scope', + duplicateScope: 'rate_limit.duplicate_scope', invalidActorKey: 'rate_limit.invalid_actor_key', invalidLimit: 'rate_limit.invalid_limit', invalidWindow: 'rate_limit.invalid_window', @@ -26,43 +28,6 @@ export interface RateLimitPolicy { windowSeconds: number; } -/** Configure one policy. Calls may override limits for application-owned dynamic policy. */ -export function client({ scope, limit, windowSeconds }: RateLimitPolicy) { - if (scope.length === 0 || scope.length > 128) - throw new Error(errors.invalidScope); - assertPositiveInt(errors.invalidLimit, limit); - assertPositiveInt(errors.invalidWindow, windowSeconds); - return { - consume( - tx: RateLimitTxLike, - opts: { - key: string; - limit?: number; - windowSeconds?: number; - cost?: number; - } - ): RateLimitResult { - if (opts.key.length === 0 || opts.key.length > 256) - throw new Error(errors.invalidActorKey); - return consumeRateLimit(tx, { - key: buildRateLimitKey(scope, opts.key), - scope, - limit: opts.limit ?? limit, - windowSeconds: opts.windowSeconds ?? windowSeconds, - cost: opts.cost, - }); - }, - }; -} - -export interface ConsumeRateLimitOpts { - key: string; - scope: string; - limit: number; - windowSeconds: number; - cost?: number; -} - export type RateLimitResult = | { allowed: true; @@ -85,32 +50,13 @@ export type RateLimitResult = retryAfterSeconds: number; }; -function assertPositiveInt(code: string, value: number): void { - if (!Number.isInteger(value) || value <= 0 || value > U32_MAX) { - throw new Error(code); - } -} - -function assertRateLimitSweepBatch(value: number): void { - assertPositiveInt(errors.invalidSweepBatch, value); - if (value > MAX_SWEEP_BATCH) { - throw new Error(errors.invalidSweepBatch); - } -} - -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); +/** Current usage of one actor's bucket. `resetAt` is unset when no window is open. */ +export interface RateLimitStatus { + limit: number; + windowSeconds: number; + used: number; + remaining: number; + resetAt: Timestamp | undefined; } export interface RateLimitBucketRow { @@ -122,6 +68,14 @@ export interface RateLimitBucketRow { updatedAt: Timestamp; } +export interface RateLimitReadDb { + rateLimitBucket: { + key: { + find(key: string): RateLimitBucketRow | null | undefined; + }; + }; +} + export interface RateLimitTxLike { timestamp: Timestamp; db: { @@ -136,113 +90,143 @@ export interface RateLimitTxLike { }; } -export function consumeRateLimit( - tx: RateLimitTxLike, - opts: ConsumeRateLimitOpts -): RateLimitResult { - assertPositiveInt(errors.invalidLimit, opts.limit); - assertPositiveInt(errors.invalidWindow, opts.windowSeconds); - const cost = opts.cost ?? 1; - assertPositiveInt(errors.invalidCost, 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, - }; +function assertPositiveInt(code: string, value: number, max = U32_MAX): void { + if (!Number.isInteger(value) || value <= 0 || value > max) { + throw new Error(code); } +} - 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), - }; +function secondsUntil(now: Timestamp, future: Timestamp): number { + const delta = future.microsSinceUnixEpoch - now.microsSinceUnixEpoch; + if (delta <= 0n) return 0; + return Number((delta + ONE_SECOND_MICROS - 1n) / ONE_SECOND_MICROS); +} + +const registeredScopes = new Set(); + +/** + * Configure the policy for one scope. Each scope may be configured once per + * module so every caller enforces the same limit and window. + */ +export function client({ scope, limit, windowSeconds }: RateLimitPolicy) { + if (scope.length === 0 || scope.length > MAX_SCOPE_LENGTH) + throw new Error(errors.invalidScope); + assertPositiveInt(errors.invalidLimit, limit); + assertPositiveInt(errors.invalidWindow, windowSeconds); + if (registeredScopes.has(scope)) throw new Error(errors.duplicateScope); + registeredScopes.add(scope); + + function bucketKey(actorKey: string): string { + if (actorKey.length === 0 || actorKey.length > MAX_ACTOR_KEY_LENGTH) + throw new Error(errors.invalidActorKey); + // Length-prefix both parts so delimiters inside them cannot collide. + return `${scope.length}:${scope}${actorKey.length}:${actorKey}`; } - 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, + scope, + limit, + windowSeconds, + + /** Spend `cost` (default 1) from the actor's bucket in the caller's transaction. */ + consume( + tx: RateLimitTxLike, + opts: { key: string; cost?: number } + ): RateLimitResult { + const key = bucketKey(opts.key); + const cost = opts.cost ?? 1; + assertPositiveInt(errors.invalidCost, cost); + const now = tx.timestamp; + const existing = tx.db.rateLimitBucket.key.find(key); + const open = + existing != null && + existing.expiresAt.microsSinceUnixEpoch > now.microsSinceUnixEpoch; + const used = open ? existing.count : 0; + const resetAt = open + ? existing.expiresAt + : new Timestamp( + now.microsSinceUnixEpoch + BigInt(windowSeconds) * ONE_SECOND_MICROS + ); + + if (used + cost > limit) { + return { + allowed: false, + key, + scope, + limit, + used, + remaining: 0, + resetAt, + retryAfterSeconds: secondsUntil(now, resetAt), + }; + } + + const row = { + key, + scope, + windowStart: open ? existing.windowStart : now, + expiresAt: resetAt, + count: used + cost, + updatedAt: now, + }; + // Update any existing row, including an expired one not yet swept. + if (existing) tx.db.rateLimitBucket.key.update(row); + else tx.db.rateLimitBucket.insert(row); + return { + allowed: true, + key, + scope, + limit, + used: row.count, + remaining: limit - row.count, + resetAt, + retryAfterSeconds: 0, + }; + }, + + /** + * Read the actor's bucket without spending from it. Views have no clock, so + * pass `now` from a reducer or procedure to report an expired window as + * fresh; without it, compare `resetAt` against the caller's clock. + */ + peek(db: RateLimitReadDb, key: string, now?: Timestamp): RateLimitStatus { + const row = db.rateLimitBucket.key.find(bucketKey(key)); + if ( + !row || + (now && row.expiresAt.microsSinceUnixEpoch <= now.microsSinceUnixEpoch) + ) { + return { + limit, + windowSeconds, + used: 0, + remaining: limit, + resetAt: undefined, + }; + } + return { + limit, + windowSeconds, + used: row.count, + remaining: Math.max(0, limit - row.count), + resetAt: row.expiresAt, + }; + }, }; } +export type RateLimitClient = ReturnType; + export function sweepRateLimits( tx: RateLimitTxLike, expiredRows: Iterable, - maxRows = DEFAULT_SWEEP_BATCH + maxRows: number ): number { - assertRateLimitSweepBatch(maxRows); - const nowMicros = tx.timestamp.microsSinceUnixEpoch as bigint; + assertPositiveInt(errors.invalidSweepBatch, maxRows, MAX_SWEEP_BATCH); + const now = tx.timestamp.microsSinceUnixEpoch; let deleted = 0; for (const row of expiredRows) { if (deleted >= maxRows) break; - if ((row.expiresAt.microsSinceUnixEpoch as bigint) > nowMicros) continue; + if (row.expiresAt.microsSinceUnixEpoch > now) continue; tx.db.rateLimitBucket.delete(row); deleted++; } diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts index 9959d2e0ac3..777b4381b7b 100644 --- a/spacetime-rate-limit-ts/src/submodule.ts +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -3,18 +3,19 @@ export { install } from './submodule/install'; export { client, errors, - consumeRateLimit, - type ConsumeRateLimitOpts, + type RateLimitClient, type RateLimitPolicy, + type RateLimitReadDb, type RateLimitResult, + type RateLimitStatus, type RateLimitTxLike, } from './limit'; -export { buildRateLimitKey } from './key'; export { adminRateLimitBuckets, addRateLimitAdmin, removeRateLimitAdmin, - consume, + isAdmin, + requireAdmin, rateLimitSweep, resetBuckets, runSweep, diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts index 7c2e0a7e814..a74647a7bff 100644 --- a/spacetime-rate-limit-ts/src/submodule/operations.ts +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -1,6 +1,6 @@ import { Range, SenderError } from 'spacetimedb/server'; +import type { Identity } from 'spacetimedb'; import { - consumeRateLimit, DEFAULT_SWEEP_BATCH, MAX_SWEEP_BATCH, sweepRateLimits, @@ -11,36 +11,22 @@ import { rateLimitSweepTick, spacetimedb, t, - type ReducerModuleCtx, type ViewModuleCtx, } from './schema'; -import { buildRateLimitKey } from '../key'; -const MAX_SCOPE_LENGTH = 128; -const MAX_ACTOR_KEY_LENGTH = 256; - -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; +/** Whether `identity` is a rate-limit administrator. */ +export function isAdmin(db: ViewModuleCtx['db'], identity: Identity): boolean { + return db.rateLimitAdminIdentity.identity.find(identity) != null; } -function requireAdmin(ctx: ReducerModuleCtx): void { - if (ctx.db.rateLimitAdminIdentity.identity.find(ctx.sender) == null) { +/** Throw `errors.notAuthorized` unless the caller is a rate-limit administrator. */ +export function requireAdmin(ctx: Pick): void { + if (!isAdmin(ctx.db, ctx.sender)) { throw new SenderError(errors.notAuthorized); } } -function toU32(code: string, value: number, max = 0xffff_ffff): number { +function positiveU32(code: string, value: number, max: number): number { if (!Number.isInteger(value) || value <= 0 || value > max) { throw new SenderError(code); } @@ -50,63 +36,9 @@ function toU32(code: string, value: number, max = 0xffff_ffff): number { function maxRowsArg(value: number | undefined): number { return value === undefined ? DEFAULT_SWEEP_BATCH - : toU32(errors.invalidMaxRows, value, MAX_SWEEP_BATCH); -} - -function sanitizePart(s: string): string { - return s.trim().replace(/\s+/g, ' '); + : positiveU32(errors.invalidMaxRows, value, MAX_SWEEP_BATCH); } -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(errors.invalidScope); - } - if (actorKey.length === 0 || actorKey.length > MAX_ACTOR_KEY_LENGTH) { - throw new SenderError(errors.invalidActorKey); - } - const limit = toU32(errors.invalidLimit, Number(args.limit)); - const windowSeconds = toU32( - errors.invalidWindow, - Number(args.windowSeconds) - ); - const cost = toU32(errors.invalidCost, 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, - }; - }); - return out; - } -); - export const runSweep = spacetimedb.procedure( { maxRows: t.option(t.u32()) }, t.u32(), @@ -159,9 +91,9 @@ export const updateConfig = spacetimedb.reducer( if (!cfg) throw new Error(errors.configMissing); ctx.db.rateLimitConfig.singleton.update({ ...cfg, - sweepBatch: toU32( + sweepBatch: positiveU32( errors.invalidSweepBatch, - Number(args.sweepBatch), + args.sweepBatch, MAX_SWEEP_BATCH ), updatedAt: ctx.timestamp, @@ -187,7 +119,7 @@ export const adminRateLimitBuckets = spacetimedb.view( { name: 'admin_rate_limit_buckets', public: true }, t.array(rateLimitBucket.rowType), ctx => { - if (!isAdmin(ctx)) return []; + if (!isAdmin(ctx.db, ctx.sender)) return []; const rows = []; for (const row of ctx.db.rateLimitBucket.iter()) { if (rows.length >= 1000) break; From a82ef553c3c7ae62a94426aed4a9a0cfb28a33ee Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:48:58 -0400 Subject: [PATCH 14/32] Replace spacetimeCron and createCron with cron client cron imports the SDK directly instead of receiving it as a parameter, so tables and types come from the real SDK and the dynamic SDK casts are gone. client({ jobs, ...options }) replaces spacetimeCron(sdk) and createCron(jobs, opts) and returns tables, schedule, unschedule, reconcileReducer, and publicViews. cronTable() stays the job declaration. cronReducer and cronProcedure infer the handler context from the host schema, and registration fails to compile when the schema lacks cron.tables. cron.tables is typed per job, so host code can read fire tables without casts. Thrown codes come from an exported errors object. Also set the unpublished package version to 0.1.0, describe Failed runs accurately, drop decorative separators from the modules, and remove allowImportingTsExtensions. --- spacetime-cron-ts/README.md | 97 +- spacetime-cron-ts/example/README.md | 6 +- .../example/spacetimedb/src/index.ts | 64 +- spacetime-cron-ts/package.json | 4 +- .../scripts/sys-abi-test-register.mjs | 24 +- .../scripts/test-registration.ts | 253 +-- spacetime-cron-ts/scripts/test-types.ts | 112 +- spacetime-cron-ts/spacetimedb/src/index.ts | 97 +- spacetime-cron-ts/src/cron.ts | 1570 +++++++---------- spacetime-cron-ts/src/errors.ts | 36 + spacetime-cron-ts/src/index.ts | 19 +- spacetime-cron-ts/src/schedule.ts | 27 +- spacetime-cron-ts/src/tables.ts | 153 ++ spacetime-cron-ts/src/types.ts | 142 +- spacetime-cron-ts/tsconfig.json | 3 +- 15 files changed, 1219 insertions(+), 1388 deletions(-) create mode 100644 spacetime-cron-ts/src/errors.ts create mode 100644 spacetime-cron-ts/src/tables.ts diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md index 902ea7b0ee0..235d7969bcf 100644 --- a/spacetime-cron-ts/README.md +++ b/spacetime-cron-ts/README.md @@ -32,27 +32,8 @@ For the complete install, build, and publish workflow, see the repository's ### 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, -}); +import { schema, table, t } from 'spacetimedb/server'; +import { client, cronTable } from '@spacetimedb/cron'; const dailyReport = cronTable({ name: 'daily_report', @@ -64,7 +45,8 @@ const dailyReport = cronTable({ const heartbeat = cronTable({ name: 'heartbeat' }); const refreshCatalog = cronTable({ name: 'refresh_catalog' }); -const cron = createCron([dailyReport, heartbeat, refreshCatalog], { +const cron = client({ + jobs: [dailyReport, heartbeat, refreshCatalog], publicTables: true, reconcileEverySeconds: 300, }); @@ -80,13 +62,9 @@ const report = table( 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, args, invocation) => { ctx.db.report.insert({ id: 0n, generatedAt: invocation.scheduledFor, @@ -97,13 +75,13 @@ export const generateReport = dailyReport.cronReducer( } ); -export const beat = heartbeat.cronReducer(spacetimedb, (_ctx: Tx) => { +export const beat = heartbeat.cronReducer(spacetimedb, _ctx => { // Perform deterministic database work here. }); export const refresh = refreshCatalog.cronProcedure( spacetimedb, - (ctx: Proc, invocation) => { + (ctx, invocation) => { // Use invocation.id as the idempotency key for an external request. ctx.http.fetch('https://example.com/catalog'); } @@ -113,13 +91,13 @@ 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', { + cron.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 * * * *'); + cron.schedule(ctx, heartbeat, { everySeconds: 30 }); + cron.schedule(ctx, refreshCatalog, '0 */15 * * * *'); }); ``` @@ -147,17 +125,18 @@ const archiveWorkspace = cronTable({ }); ``` -The handle carries the inferred argument type through `schedule()`, +The handle carries the inferred argument type through `cron.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()`. +every handle to one `client()` call when the module loads, then register +exactly one reducer or procedure for each handle after `schema()`. +`cron.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. @@ -165,12 +144,15 @@ 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`: +Use `cronReducer` for deterministic database work. The handler receives the +host module's reducer context, inferred from `spacetimedb`, and a +`CronInvocation`. Registration fails to compile if the schema does not include +`cron.tables`: ```ts export const runCleanup = cleanup.cronReducer( spacetimedb, - (ctx: Tx, invocation) => { + (ctx, invocation) => { console.log(invocation.id); // Database writes commit together when the handler succeeds. } @@ -182,7 +164,7 @@ Use `cronProcedure` for HTTP requests and other procedure capabilities: ```ts export const syncRemote = remoteSync.cronProcedure( spacetimedb, - (ctx: Proc, invocation) => { + (ctx, invocation) => { sendRequest({ idempotencyKey: invocation.id }); } ); @@ -196,7 +178,7 @@ metadata: ```ts export const runArchive = archiveWorkspace.cronReducer( spacetimedb, - (ctx: Tx, args, invocation) => { + (ctx, args, invocation) => { archiveRows(ctx, args.workspaceId, args.retainDays); console.log(invocation.id); } @@ -205,15 +187,15 @@ export const runArchive = archiveWorkspace.cronReducer( ### Scheduling and cancellation -`schedule()` first repairs any enabled jobs with missing triggers. It then +`cron.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 }); +cron.schedule(ctx, cleanup, '30 2 * * *', { timezone: 'UTC' }); +cron.schedule(ctx, cleanup, { everySeconds: 300 }); -schedule(ctx, archiveWorkspace, '0 3 * * *', { +cron.schedule(ctx, archiveWorkspace, '0 3 * * *', { timezone: 'UTC', args: { workspaceId: 42n, retainDays: 90 }, }); @@ -225,16 +207,21 @@ 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. +`cron.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); +cron.unschedule(ctx, cleanup); ``` These helpers perform scheduling operations. Application reducers remain responsible for authorization. +Input errors from `cron.schedule()` are thrown as `SenderError`s. Every code +thrown by the package is exported as `errors`, for example +`errors.invalidExpression` (`cron.invalid_expression`). Codes may be followed +by `:` and detail text. + ### Database state The package adds these shared tables: @@ -297,11 +284,11 @@ 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: +`cron.schedule()` and `cron.unschedule()` operation. Set +`reconcileEverySeconds` to add a low-frequency native interval sweep: ```ts -const cron = createCron(jobs, { reconcileEverySeconds: 300 }); +const cron = client({ jobs, reconcileEverySeconds: 300 }); // Export after registering the job handlers. export const cronReconcile = cron.reconcileReducer(spacetimedb); @@ -350,8 +337,8 @@ Scheduled functions execute through SpacetimeDB's scheduler. A long-running proc Run statuses are: -- `Ok`: work completed successfully -- `Failed`: the handler returned an error +- `Ok`: the handler completed without throwing +- `Failed`: the handler threw, or reconciliation recorded a lost fire ### Parser exports diff --git a/spacetime-cron-ts/example/README.md b/spacetime-cron-ts/example/README.md index 339e2d3d2fe..5119d5587a2 100644 --- a/spacetime-cron-ts/example/README.md +++ b/spacetime-cron-ts/example/README.md @@ -90,7 +90,7 @@ The browser connects directly to SpacetimeDB. The Express process serves static 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 +2. `client()` 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. @@ -99,7 +99,7 @@ The browser connects directly to SpacetimeDB. The Express process serves static 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()`. + selected job and typed cleanup argument before calling `cron.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. @@ -119,7 +119,7 @@ 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 +Calls to `cron.schedule()` and `cron.unschedule()` also perform this repair opportunistically. Typed arguments remain in the private `cron_job` row. The browser-visible diff --git a/spacetime-cron-ts/example/spacetimedb/src/index.ts b/spacetime-cron-ts/example/spacetimedb/src/index.ts index 574fd6ae53f..eeabd879ede 100644 --- a/spacetime-cron-ts/example/spacetimedb/src/index.ts +++ b/spacetime-cron-ts/example/spacetimedb/src/index.ts @@ -1,27 +1,5 @@ -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 ───────────────────────────────────────────────────────────────────── +import { schema, table, t, SenderError } from 'spacetimedb/server'; +import { client, cronTable, type CronJobReference } from '@spacetimedb/cron'; const digest = cronTable({ name: 'digest' }); const cleanup = cronTable({ @@ -29,13 +7,12 @@ const cleanup = cronTable({ args: t.object('CleanupCronArgs', { keep: t.u32() }), }); -const cron = createCron([digest, cleanup], { +const cron = client({ + jobs: [digest, cleanup], publicTables: true, reconcileEverySeconds: 300, }); -// ── App tables ─────────────────────────────────────────────────────────────── - const activityLog = table( { name: 'activity_log', public: true }, { @@ -49,12 +26,7 @@ const activityLog = table( 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) => { +export const runDigest = digest.cronReducer(spacetimedb, ctx => { const entries = ctx.db.activityLog.count(); ctx.db.activityLog.insert({ id: 0n, @@ -64,7 +36,7 @@ export const runDigest = digest.cronReducer(spacetimedb, (ctx: Tx) => { }); }); -export const runCleanup = cleanup.cronReducer(spacetimedb, (ctx: Tx, args) => { +export const runCleanup = cleanup.cronReducer(spacetimedb, (ctx, args) => { const total = Number(ctx.db.activityLog.count()); if (total <= args.keep) return; const excess = total - args.keep + 1; @@ -92,12 +64,10 @@ 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 } }); + cron.schedule(ctx, digest, '0 9 * * 1-5', { timezone: 'America/New_York' }); + cron.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. @@ -105,7 +75,7 @@ const jobs: Record = { digest, cleanup }; function jobByName(name: string): CronJobReference { const job = jobs[name]; - if (!job) throw new SenderError(`cron.unknown_job:${name}`); + if (!job) throw new SenderError(`example.unknown_job:${name}`); return job; } @@ -126,14 +96,16 @@ export const scheduleCron = spacetimedb.reducer( (ctx, args) => { try { if (args.name === 'cleanup') { - schedule(ctx, cleanup, args.expression, { + cron.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 }); + cron.schedule(ctx, digest, args.expression, { + timezone: args.timezone, + }); } else { - throw new SenderError(`cron.unknown_job:${args.name}`); + throw new SenderError(`example.unknown_job:${args.name}`); } } catch (err) { throw err instanceof SenderError @@ -148,16 +120,16 @@ export const scheduleEvery = spacetimedb.reducer( (ctx, args) => { try { if (args.name === 'cleanup') { - schedule( + cron.schedule( ctx, cleanup, { everySeconds: args.seconds }, { args: { keep: cleanupKeep(args.keep) } } ); } else if (args.name === 'digest') { - schedule(ctx, digest, { everySeconds: args.seconds }); + cron.schedule(ctx, digest, { everySeconds: args.seconds }); } else { - throw new SenderError(`cron.unknown_job:${args.name}`); + throw new SenderError(`example.unknown_job:${args.name}`); } } catch (err) { throw err instanceof SenderError @@ -170,6 +142,6 @@ export const scheduleEvery = spacetimedb.reducer( export const unscheduleJob = spacetimedb.reducer( { name: t.string() }, (ctx, { name }) => { - unschedule(ctx, jobByName(name)); + cron.unschedule(ctx, jobByName(name)); } ); diff --git a/spacetime-cron-ts/package.json b/spacetime-cron-ts/package.json index 68acfcd02b6..4b7175a6dfb 100644 --- a/spacetime-cron-ts/package.json +++ b/spacetime-cron-ts/package.json @@ -1,7 +1,7 @@ { "name": "@spacetimedb/cron", "description": "Calendar and interval scheduling for SpacetimeDB TypeScript modules.", - "version": "0.3.0", + "version": "0.1.0", "license": "Apache-2.0", "type": "module", "main": "./src/index.ts", @@ -47,7 +47,7 @@ "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:registration": "node --js-explicit-resource-management --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", diff --git a/spacetime-cron-ts/scripts/sys-abi-test-register.mjs b/spacetime-cron-ts/scripts/sys-abi-test-register.mjs index 556603c3447..6a9b9e9d245 100644 --- a/spacetime-cron-ts/scripts/sys-abi-test-register.mjs +++ b/spacetime-cron-ts/scripts/sys-abi-test-register.mjs @@ -1,15 +1,23 @@ import { register } from 'node:module'; -const loaderSource = ` - const sysAbiUrl = 'data:text/javascript,' + encodeURIComponent( - 'export function volatile_nonatomic_schedule_immediate() {}' - ); +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {} export function volatile_nonatomic_schedule_immediate() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; export function resolve(specifier, context, nextResolve) { - if (specifier === 'spacetime:sys@2.0') { - return { shortCircuit: true, url: sysAbiUrl }; - } - return nextResolve(specifier, context); + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); } `; diff --git a/spacetime-cron-ts/scripts/test-registration.ts b/spacetime-cron-ts/scripts/test-registration.ts index 8c2b182d8bc..1c3162b7863 100644 --- a/spacetime-cron-ts/scripts/test-registration.ts +++ b/spacetime-cron-ts/scripts/test-registration.ts @@ -1,151 +1,119 @@ import * as assert from 'node:assert/strict'; -import { spacetimeCron } from '../src/cron'; -import type { CronSchema, CronSdk } from '../src/types'; +import { schema } from 'spacetimedb/server'; +import { client, cronTable, publicDisabledReason } from '../src/cron'; +import { errors } from '../src/errors'; -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 expectCode = (code: string) => ({ + message: new RegExp(`^${code}(:|$)`), +}); { - const owner = createApi(); - const foreign = createApi().cronTable({ name: 'foreign' }); - assert.throws(() => owner.createCron([foreign]), /cron\.foreign_job_handle/); + const job = cronTable({ name: 'owned' }); + const other = cronTable({ name: 'other' }); + const cron = client({ jobs: [job] }); + client({ jobs: [other] }); + assert.throws( + () => cron.unschedule({} as never, other), + expectCode(errors.foreignJobHandle) + ); + assert.throws( + () => client({ jobs: [{ jobName: 'plain' }] }), + expectCode(errors.foreignJobHandle) + ); } +assert.throws(() => client({ jobs: [] }), expectCode(errors.noJobs)); + { - const api = createApi(); - const job = api.cronTable({ name: 'duplicate' }); - assert.throws( - () => api.createCron([job, job]), - /cron\.duplicate_job:duplicate/ - ); + const job = cronTable({ name: 'duplicate' }); + assert.throws(() => client({ jobs: [job, job] }), { + message: /^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 job = cronTable({ name: 'wired_once' }); + client({ jobs: [job] }); + assert.throws(() => client({ jobs: [job] }), { + message: /^cron\.job_already_wired:wired_once$/, + }); } { - const api = createApi(); - const job = api.cronTable({ name: 'not_wired' }); - assert.throws( - () => job.cronReducer(registrationSchema, () => {}), - /cron\.not_wired:not_wired/ - ); + const job = cronTable({ name: 'not_wired' }); + const other = client({ jobs: [cronTable({ name: 'other_client' })] }); + const spacetimedb = schema({ ...other.tables }); + assert.throws(() => job.cronReducer(spacetimedb, () => {}), { + message: /^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 job = cronTable({ name: 'missing_handler' }); + const cron = client({ jobs: [job], reconcileEverySeconds: 60 }); + const spacetimedb = schema({ ...cron.tables }); + assert.throws(() => cron.reconcileReducer(spacetimedb), { + message: /^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 job = cronTable({ name: 'unscheduled_handler' }); + const cron = client({ jobs: [job] }); + assert.throws(() => cron.schedule({} as never, job, { everySeconds: 60 }), { + message: /^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 job = cronTable({ name: 'duplicate_handler' }); + const cron = client({ jobs: [job] }); + const spacetimedb = schema({ ...cron.tables }); + job.cronReducer(spacetimedb, () => {}); + assert.throws(() => job.cronProcedure(spacetimedb, () => {}), { + message: /^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, () => {}); + const job = cronTable({ name: 'no_reconciler' }); + const cron = client({ jobs: [job] }); + const spacetimedb = schema({ ...cron.tables }); + job.cronReducer(spacetimedb, () => {}); assert.throws( - () => cron.reconcileReducer(registrationSchema), - /cron\.reconcile_not_configured/ + () => cron.reconcileReducer(spacetimedb), + expectCode(errors.reconcileNotConfigured) ); } { - const api = createApi(); - const job = api.cronTable({ name: 'reconcile_once' }); - const cron = api.createCron([job], { reconcileEverySeconds: 60 }); - job.cronReducer(registrationSchema, () => {}); - cron.reconcileReducer(registrationSchema); + const job = cronTable({ name: 'reconcile_once' }); + const cron = client({ jobs: [job], reconcileEverySeconds: 60 }); + const spacetimedb = schema({ ...cron.tables }); + job.cronReducer(spacetimedb, () => {}); + cron.reconcileReducer(spacetimedb); assert.throws( - () => cron.reconcileReducer(registrationSchema), - /cron\.reconcile_reducer_already_registered/ + () => cron.reconcileReducer(spacetimedb), + expectCode(errors.reconcileReducerAlreadyRegistered) ); } { - const api = createApi(); - const job = api.cronTable({ name: 'views_once' }); - const cron = api.createCron([job]); - cron.publicViews(registrationSchema); + const job = cronTable({ name: 'views_once' }); + const cron = client({ jobs: [job] }); + const spacetimedb = schema({ ...cron.tables }); + cron.publicViews(spacetimedb); assert.throws( - () => cron.publicViews(registrationSchema), - /cron\.public_views_already_registered/ + () => cron.publicViews(spacetimedb), + expectCode(errors.publicViewsAlreadyRegistered) ); } { - const api = createApi(); - const firstJob = api.cronTable({ name: 'first_job' }); - const secondJob = api.cronTable({ name: 'second_job' }); - const cron = api.createCron([firstJob, secondJob], { + const firstJob = cronTable({ name: 'first_job' }); + const secondJob = cronTable({ name: 'second_job' }); + const cron = client({ + jobs: [firstJob, secondJob], reconcileEverySeconds: 60, }); assert.deepEqual(Object.keys(cron.tables).sort(), [ @@ -157,62 +125,23 @@ function createApi() { ]); } -{ - 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 = [ +assert.deepEqual( + [ 'failed_1_consecutive_times:secret application failure', 'failed_1_consecutive_times:lost_fire', - 'cron.invalid_schedule_state:secret parser detail', + `${errors.invalidScheduleState}: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', - ] - ); -} + undefined, + ].map(publicDisabledReason), + [ + 'failure_threshold_reached', + 'lost_fire_threshold_reached', + 'invalid_schedule_state', + 'disabled_by_operator', + 'disabled', + undefined, + ] +); -console.log('cron registration tests passed'); +process.stdout.write('cron registration tests passed\n'); diff --git a/spacetime-cron-ts/scripts/test-types.ts b/spacetime-cron-ts/scripts/test-types.ts index eab0bbebaee..210248f9f65 100644 --- a/spacetime-cron-ts/scripts/test-types.ts +++ b/spacetime-cron-ts/scripts/test-types.ts @@ -1,72 +1,78 @@ // Compile-time API coverage. This file is checked by `pnpm typecheck`. -import { t } from 'spacetimedb/server'; -import type { - CronApi, - CronInvocation, - CronJobReference, - CronSchema, +import { schema, t, table } from 'spacetimedb/server'; +import { + client, + cronTable, + type CronInvocation, + type CronJobReference, } from '../src/index'; -declare const cron: CronApi; -declare const ctx: object; -declare const spacetimedb: CronSchema; - -const heartbeat = cron.cronTable({ name: 'heartbeat' }); -const reportDefinition = { +const heartbeat = cronTable({ name: 'heartbeat' }); +const report = cronTable({ 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; }); +const cron = client({ + jobs: [heartbeat, report], + reconcileEverySeconds: 300, +}); +const log = table({ name: 'log' }, { id: t.u64().primaryKey() }); +const spacetimedb = schema({ ...cron.tables, log }); -report.cronReducer(spacetimedb, (_ctx: object, args, invocation) => { - const tenantId: bigint = args.tenantId; - const batchSize: number = args.batchSize; +export const beat = heartbeat.cronReducer(spacetimedb, (ctx, invocation) => { + ctx.db.log.insert({ id: invocation.sequence }); + ctx.db.heartbeatFire.jobName.find('heartbeat'); 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: {}, +export const runReport = report.cronProcedure( + spacetimedb, + (ctx, args, invocation) => { + const tenantId: bigint = args.tenantId; + const batchSize: number = args.batchSize; + ctx.withTx(tx => tx.db.log.insert({ id: tenantId })); + void batchSize; + void invocation; } ); -const reference: CronJobReference = report; -cron.unschedule(ctx, reference); +export const init = spacetimedb.init(ctx => { + 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 }, + }); -const core = cron.createCron([heartbeat, report], { - reconcileEverySeconds: 300, + // @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 reconcile = core.reconcileReducer(spacetimedb); -const publicViews = core.publicViews(spacetimedb); -void reconcile; -void publicViews.jobs; + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +// A schema without the cron tables cannot register cron handlers. +// @ts-expect-error The host schema must include cron.tables. +heartbeat.cronReducer(schema({ log }), () => {}); diff --git a/spacetime-cron-ts/spacetimedb/src/index.ts b/spacetime-cron-ts/spacetimedb/src/index.ts index 397e76ea4e2..facc80abeb5 100644 --- a/spacetime-cron-ts/spacetimedb/src/index.ts +++ b/spacetime-cron-ts/spacetimedb/src/index.ts @@ -1,33 +1,11 @@ +import { schema, table, t, SenderError } from 'spacetimedb/server'; import { - schema, - table, - t, - SenderError, - toCamelCase, - type ReducerCtx, - type InferSchema, - type ProcedureCtx, -} from 'spacetimedb/server'; -import { ScheduleAt, Timestamp } from 'spacetimedb'; -import { - spacetimeCron, + client, + cronTable, 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', @@ -43,13 +21,12 @@ const probe = cronTable({ }); const recoveryProbe = cronTable({ name: 'recovery_probe' }); -const cron = createCron([heartbeat, report, flaky, probe, recoveryProbe], { +const cron = client({ + jobs: [heartbeat, report, flaky, probe, recoveryProbe], publicTables: true, reconcileEverySeconds: 2, }); -// ── App tables ─────────────────────────────────────────────────────────────── - const tickLog = table( { name: 'tick_log', public: true }, { @@ -95,19 +72,13 @@ const spacetimedb = schema({ }); export default spacetimedb; -type Schema = InferSchema; -type Tx = ReducerCtx; -type Proc = ProcedureCtx; - -// ── Cron wiring ────────────────────────────────────────────────────────────── - -export const runHeartbeat = heartbeat.cronReducer(spacetimedb, (ctx: Tx) => { +export const runHeartbeat = heartbeat.cronReducer(spacetimedb, ctx => { ctx.db.tickLog.insert({ id: 0n, jobName: 'heartbeat', at: ctx.timestamp }); }); export const runReport = report.cronReducer( spacetimedb, - (ctx: Tx, args, invocation) => { + (ctx, args, invocation) => { ctx.db.tickLog.insert({ id: 0n, jobName: 'report', at: ctx.timestamp }); ctx.db.argumentLog.insert({ id: 0n, @@ -122,21 +93,14 @@ export const runReport = report.cronReducer( // 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 }); + const fire = ctx.db.reportFire.jobName.find('report'); + if (!fire) throw new SenderError('test.missing_report_fire'); + runReport(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) => { +export const runFlaky = flaky.cronReducer(spacetimedb, ctx => { 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'); @@ -146,12 +110,12 @@ export const runFlaky = flaky.cronReducer(spacetimedb, (ctx: Tx) => { // HTTP. Here it writes through withTx so the local suite can observe it. export const runProbe = probe.cronProcedure( spacetimedb, - (ctx: Proc, args, invocation) => { + (ctx, args, invocation) => { const failing = ctx.withTx( - (tx: Tx) => tx.db.flakyState.singleton.find(true)?.failing ?? false + tx => tx.db.flakyState.singleton.find(true)?.failing ?? false ); if (failing) throw new Error('probe.failure'); - ctx.withTx((tx: Tx) => { + ctx.withTx(tx => { tx.db.tickLog.insert({ id: 0n, jobName: 'probe', at: tx.timestamp }); tx.db.argumentLog.insert({ id: 0n, @@ -175,9 +139,9 @@ function blockUntilHostStops(): never { // host. Its separate transactions prove what survives the interruption. export const runRecoveryProbe = recoveryProbe.cronProcedure( spacetimedb, - (ctx: Proc, run) => { + (ctx, run) => { if (run.sequence === 1n) { - ctx.withTx((tx: Tx) => { + ctx.withTx(tx => { tx.db.recoveryProbeState.insert({ singleton: true, invocationId: run.id, @@ -185,7 +149,7 @@ export const runRecoveryProbe = recoveryProbe.cronProcedure( }); blockUntilHostStops(); } - ctx.withTx((tx: Tx) => { + ctx.withTx(tx => { tx.db.tickLog.insert({ id: 0n, jobName: 'recovery_probe', @@ -201,10 +165,10 @@ 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 }); + cron.schedule(ctx, heartbeat, { everySeconds: 30 }); }); -// ── CLI-facing management (thin wrappers over the library helpers) ─────────── +// CLI-facing management over the library helpers. const argumentlessJobs: Record = { heartbeat, @@ -220,13 +184,13 @@ const allJobs: Record = { function argumentlessJobByName(name: string): CronJobHandle { const job = argumentlessJobs[name]; - if (!job) throw new SenderError(`cron.unknown_job:${name}`); + if (!job) throw new SenderError(`test.unknown_job:${name}`); return job; } function jobByName(name: string): CronJobReference { const job = allJobs[name]; - if (!job) throw new SenderError(`cron.unknown_job:${name}`); + if (!job) throw new SenderError(`test.unknown_job:${name}`); return job; } @@ -249,7 +213,7 @@ export const scheduleCron = spacetimedb.reducer( }, (ctx, args) => { scheduleSafely(() => { - schedule(ctx, argumentlessJobByName(args.name), args.expression, { + cron.schedule(ctx, argumentlessJobByName(args.name), args.expression, { timezone: args.timezone, maxFailures: args.maxFailures, }); @@ -261,7 +225,7 @@ export const scheduleEvery = spacetimedb.reducer( { name: t.string(), seconds: t.u32(), maxFailures: t.u32() }, (ctx, args) => { scheduleSafely(() => { - schedule( + cron.schedule( ctx, argumentlessJobByName(args.name), { everySeconds: args.seconds }, @@ -281,7 +245,7 @@ export const scheduleReport = spacetimedb.reducer( }, (ctx, args) => { scheduleSafely(() => { - schedule(ctx, report, args.expression, { + cron.schedule(ctx, report, args.expression, { timezone: args.timezone, maxFailures: args.maxFailures, args: { label: args.label, batchSize: args.batchSize }, @@ -299,7 +263,7 @@ export const scheduleProbe = spacetimedb.reducer( }, (ctx, args) => { scheduleSafely(() => { - schedule(ctx, probe, args.expression, { + cron.schedule(ctx, probe, args.expression, { timezone: args.timezone, maxFailures: args.maxFailures, args: { source: args.source }, @@ -311,7 +275,7 @@ export const scheduleProbe = spacetimedb.reducer( export const unscheduleJob = spacetimedb.reducer( { name: t.string() }, (ctx, { name }) => { - unschedule(ctx, jobByName(name)); + cron.unschedule(ctx, jobByName(name)); } ); @@ -325,12 +289,5 @@ export const setFlakyFailing = spacetimedb.reducer( // 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); + ctx.db.heartbeatFire.jobName.delete('heartbeat'); }); diff --git a/spacetime-cron-ts/src/cron.ts b/spacetime-cron-ts/src/cron.ts index bd8dc087de5..6b264cbcd8f 100644 --- a/spacetime-cron-ts/src/cron.ts +++ b/spacetime-cron-ts/src/cron.ts @@ -1,8 +1,16 @@ // 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 { BinaryWriter, Timestamp } from 'spacetimedb'; +import { + ScheduleAt, + SenderError, + t, + toCamelCase, + type Infer, + type VariantsObj, +} from 'spacetimedb/server'; +import { errors } from './errors'; import { boundedScheduleTime, CronInputError, @@ -17,22 +25,32 @@ import { ONE_SECOND_MICROS, truncateError, } from './schedule'; +import { + cronFireTable, + cronJobTable, + cronJobView, + cronReconcileTickTable, + cronRunTable, + type CronFireTable, + type CronFireTableDef, + type CronProcedureCtx, + type CronReconcileTickTableDef, + type CronTx, + type FireRow, + type JobRow, +} from './tables'; import type { - CronApi, CronArgsBuilder, - CronCore, - CronCorePublicViews, + CronClient, + CronConfig, CronInvocation, CronJobHandle, CronJobReference, - CronSchedule, + CronPublicViews, CronSchema, - CronSdk, - CronTableDefinition, CronTableOpts, CronTableWithArgsOpts, - CronTimestamp, - CreateCronOpts, + CronTables, ScheduleSpec, } from './types'; @@ -49,73 +67,14 @@ const PUBLIC_DISABLED_REASONS = { 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 { +export 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:')) { + if (reason.startsWith(`${errors.invalidScheduleState}:`)) { return PUBLIC_DISABLED_REASONS.invalidScheduleState; } if (/^failed_[1-9][0-9]*_consecutive_times:lost_fire$/.test(reason)) { @@ -127,93 +86,31 @@ function publicDisabledReason(reason: string | undefined): string | undefined { 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; -} +type InternalHandler = (...args: unknown[]) => unknown; -interface ProcedureContext { - readonly timestamp: CronTimestamp; - readonly sender: IdentityLike; - readonly databaseIdentity: IdentityLike; - withTx(body: (ctx: TransactionContext) => T): T; +interface RuntimeScheduleOpts { + timezone?: string; + maxFailures?: number; + args?: unknown; } interface JobMetadata { readonly handle: CronJobReference; - readonly argsType: DynamicSdkValue; + readonly argsType: CronArgsBuilder; readonly hasArgs: boolean; readonly fireTableName: string; readonly fireAccessor: string; readonly reducerName: string; - fire: DynamicSdkValue | undefined; - core: InternalCore | undefined; + fire: CronFireTableDef | undefined; + core: Core | undefined; registration: 'reducer' | 'procedure' | undefined; } -interface InternalCore extends CronCore { +interface Core { readonly jobs: Map; readonly historyCap: number; readonly reconcileEverySeconds: number | undefined; - readonly reconcileTick: DynamicSdkValue | undefined; + readonly reconcileTick: CronReconcileTickTableDef | undefined; reconcileRegistered: boolean; publicViewsRegistered: boolean; } @@ -223,12 +120,14 @@ interface PreparedFire { readonly args: unknown; } +const metadata = new WeakMap(); + 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' + typeof value.then === 'function' ); } @@ -240,832 +139,711 @@ function invocationId( 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 requireMetadata(job: CronJobReference): JobMetadata { + const value = metadata.get(job); + if (!value) throw new Error(errors.foreignJobHandle); + 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 requireCore(job: CronJobReference): Core { + const value = requireMetadata(job).core; + if (!value) { + throw new Error( + `${errors.notWired}:${job.jobName}:pass the job to client() first` + ); } + return value; +} - 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 requireRegisteredHandlers(core: Core): void { + const missing = [...core.jobs.values()] + .filter(job => !job.registration) + .map(job => job.handle.jobName); + if (missing.length > 0) { + throw new Error(`${errors.missingHandlers}:${missing.join(',')}`); } +} - function asTransactionContext(ctx: unknown): TransactionContext { - return ctx as TransactionContext; +function requireFire(job: JobMetadata): CronFireTableDef { + if (!job.fire) { + throw new Error( + `${errors.notWired}:${job.handle.jobName}:pass the job to client() first` + ); } + return job.fire; +} - function requireDatabaseCaller( - ctx: Pick - ): void { - if (ctx.sender.toHexString() !== ctx.databaseIdentity.toHexString()) { - throw new SenderError('cron.not_authorized'); - } +function requireDatabaseCaller( + ctx: Pick +): void { + if (!ctx.sender.isEqual(ctx.databaseIdentity)) { + throw new SenderError(errors.notAuthorized); } +} - 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 fireTable(ctx: CronTx, job: JobMetadata): CronFireTable { + const value = ctx.db[job.fireAccessor]; + if (!value) { + throw new Error( + `${errors.missingTable}:${job.fireTableName}:spread cron.tables into schema()` + ); } + // The accessor was derived from the fire table registered by client(). + return value as CronFireTable; +} - function throwInputError(error: unknown): never { - if (error instanceof CronInputError) { - throw new SenderError(error.message); - } - throw error; - } +function jobArgs(row: JobRow): unknown { + return 'value' in row.args ? row.args.value : undefined; +} - 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 pruneHistory(ctx: CronTx, core: Core, 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 recordRun( + ctx: CronTx, + core: Core, + 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 disarmFire(ctx: CronTx, 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); +function insertFire( + ctx: CronTx, + job: JobMetadata, + row: JobRow, + targetMicros: bigint | undefined +): Timestamp | undefined { + const tableView = fireTable(ctx, job); + if (row.schedule.tag === 'every') { tableView.insert({ scheduledId: 0n, - scheduledAt: ScheduleAt.time( - boundedScheduleTime(ctx.timestamp.microsSinceUnixEpoch, targetMicros) + scheduledAt: ScheduleAt.interval( + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS ), jobName: row.name, generation: row.generation, - targetAt, + targetAt: undefined, recovery: undefined, }); - return targetAt; + 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); +function replaceFire(ctx: CronTx, 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'); - } + let targetMicros: bigint | undefined; + if (row.schedule.tag === 'cron') { + try { + targetMicros = nextOccurrence( + row.schedule, + ctx.timestamp.microsSinceUnixEpoch + ); + } catch (error) { + return disableJob( + ctx, + job, + row, + `${errors.invalidScheduleState}:${truncateError(error)}` + ); } + if (targetMicros === undefined) { + return disableJob(ctx, job, row, errors.noFutureOccurrence); + } + } - const nextRunAt = insertFire(ctx, job, row, targetMicros); - const updated = { ...row, nextRunAt }; - ctx.db.cronJob.name.update(updated); - return updated; + const nextRunAt = insertFire(ctx, job, row, targetMicros); + const updated = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(updated); + return updated; +} + +function ensureReconcileTick(ctx: CronTx, core: Core): void { + const everySeconds = core.reconcileEverySeconds; + if (everySeconds === undefined) return; + if (!core.reconcileRegistered) { + throw new Error( + `${errors.reconcileReducerNotRegistered}:export cron.reconcileReducer()` + ); + } + const tick = ctx.db.cronReconcileTick; + if (!tick) { + throw new Error( + `${errors.missingTable}: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 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()' - ); +function reconcileLostFires(ctx: CronTx, core: Core): 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; } - const tick = ctx.db.cronReconcileTick; - if (!tick) { - throw new Error( - 'cron.missing_table:cron_reconcile_tick:spread cron.tables into schema()' - ); + if (row.args.tag !== job.handle.jobName) { + disableJob(ctx, job, row, errors.invalidArgsState); + continue; } - 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 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); - } + 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 = { +function disableJob( + ctx: CronTx, + 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: CronTx, + core: Core, + 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, - enabled: false, - nextRunAt: undefined, - disabledReason: truncateError(reason), + fireCount: + invocation.sequence > row.fireCount + ? invocation.sequence + : row.fireCount, + consecutiveFailures, + lastRunAt: ctx.timestamp, }; - ctx.db.cronJob.name.update(updated); - return updated; + 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}` + ); + } } - 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; + recordRun(ctx, core, invocation, status, error); +} - 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}` - ); - } +function prepareFire( + ctx: CronTx, + 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, errors.invalidArgsState); + return; + } + + const nowMicros = ctx.timestamp.microsSinceUnixEpoch; + let scheduledFor = ctx.timestamp; + if (row.schedule.tag === 'cron') { + if (!arg.targetAt) { + disableJob(ctx, job, row, `${errors.invalidTrigger}:missing_target`); + return; } + const tableView = fireTable(ctx, job); + const fired = tableView.scheduledId.find(arg.scheduledId); + if (fired) tableView.delete(fired); - 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'); + const targetMicros = arg.targetAt.microsSinceUnixEpoch; + if (targetMicros > nowMicros) { + const nextRunAt = insertFire(ctx, job, row, targetMicros); + ctx.db.cronJob.name.update({ ...row, nextRunAt }); 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); - } + scheduledFor = arg.targetAt; + const nextAt = nextOccurrence(row.schedule, nowMicros); + if (nextAt === undefined) { + row = disableJob(ctx, job, row, errors.noFutureOccurrence); } else { - const nextRunAt = new Timestamp( - nowMicros + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS - ); + const nextRunAt = insertFire(ctx, job, row, nextAt); 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(); + } else { + const nextRunAt = new Timestamp( + nowMicros + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ); + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); } - 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) - ); + const sequence = row.fireCount + 1n; + if (reserveSequence) { + row = { ...row, fireCount: sequence }; + ctx.db.cronJob.name.update(row); } + return { + args: jobArgs(row), + invocation: { + id: invocationId(row.name, row.generation, sequence), + jobName: row.name, + generation: row.generation, + sequence, + scheduledFor, + }, + }; +} - 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; +function invokeHandler( + handler: InternalHandler, + ctx: unknown, + job: JobMetadata, + prepared: PreparedFire +): unknown { + return job.hasArgs + ? handler(ctx, prepared.args, prepared.invocation) + : handler(ctx, prepared.invocation); +} - 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; - } +function encodeFireArgument(job: JobMetadata, arg: FireRow): Uint8Array { + 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. + requireFire(job).rowType.serialize(writer, arg); + return writer.getBuffer(); +} - applyOutcome(ctx, core, job, prepared.invocation, 'Ok', undefined, true); - } +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 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'); +function executeReducer( + ctx: CronTx, + core: Core, + job: JobMetadata, + arg: FireRow, + handler: InternalHandler +): void { + 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, ctx, job, prepared); + if (isThenable(result)) { + throw new Error( + `${errors.asyncReducerHandler}:reducers must complete synchronously` + ); } - const prepared = ctx.withTx(tx => prepareFire(tx, job, arg, true)); - if (!prepared) return; - - let error: string | undefined; + } catch (error) { + const detail = truncateError(error); 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); + scheduleRecovery(job, arg, prepared.invocation, detail); + } catch { + // Volatile recovery is best effort. Reconciliation repairs a missing + // calendar fire if the host loses this request. } - - ctx.withTx(tx => { - applyOutcome( - tx, - core, - job, - prepared.invocation, - error === undefined ? 'Ok' : 'Failed', - error, - false - ); - }); + throw error; } - 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; - } + applyOutcome(ctx, core, job, prepared.invocation, 'Ok', undefined, true); +} - 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 +function executeProcedure( + ctx: CronProcedureCtx, + core: Core, + job: JobMetadata, + arg: FireRow, + handler: InternalHandler +): void { + requireDatabaseCaller(ctx); + if (arg.recovery) { + throw new SenderError(errors.invalidProcedureRecovery); + } + const prepared = ctx.withTx(tx => prepareFire(tx, job, arg, true)); + if (!prepared) return; + + let error: string | undefined; + try { + const result = invokeHandler(handler, ctx, job, prepared); + if (isThenable(result)) { + throw new Error( + `${errors.asyncProcedureHandler}:procedures must complete synchronously` ); - row = { ...row, nextRunAt }; - ctx.db.cronJob.name.update(row); } + } catch (caught) { + error = truncateError(caught); + } - const invocation: CronInvocation = { - id: invocationId(jobName, arg.generation, recovery.sequence), - jobName, - generation: arg.generation, - sequence: recovery.sequence, - scheduledFor: recovery.scheduledFor, - }; + ctx.withTx(tx => { applyOutcome( - ctx, + tx, core, job, - invocation, - 'Failed', - truncateError(recovery.error), - true + prepared.invocation, + error === undefined ? 'Ok' : 'Failed', + error, + false ); - } + }); +} - 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 recoverFailure( + ctx: CronTx, + core: Core, + 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); } - 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; - } + 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 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 +function registerJob(job: JobMetadata, kind: 'reducer' | 'procedure'): Core { + const core = requireCore(job.handle); + if (job.registration) { + throw new Error( + `${errors.handlerAlreadyRegistered}:${job.handle.jobName}:${job.registration}` ); + } + job.registration = kind; + return core; +} - 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) { +/** Declare a job. Pass every job to `client()` before registering handlers. */ +export function cronTable< + const Name extends string, + ArgsBuilder extends CronArgsBuilder, +>( + opts: CronTableWithArgsOpts +): CronJobHandle>; +export function cronTable( + opts: CronTableOpts +): CronJobHandle; +export function cronTable( + opts: CronTableOpts | CronTableWithArgsOpts +): CronJobReference { + const jobName = normalizeJobName(opts.name); + const hasArgs = 'args' in opts; + const handle = { + jobName, + cronReducer(spacetimedb: CronSchema, handler: InternalHandler) { 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(), + const core = registerJob(job, 'reducer'); + const fire = requireFire(job); + return spacetimedb.reducer( + { name: job.reducerName, onSchedule: fire }, + { arg: fire.rowType }, + (ctx: CronTx, { arg }: { arg: FireRow }) => { + executeReducer(ctx, core, job, arg, handler); } ); - 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), + }, + cronProcedure(spacetimedb: CronSchema, handler: InternalHandler) { + const job = requireMetadata(handle); + const core = registerJob(job, 'procedure'); + const fire = requireFire(job); + return spacetimedb.procedure( + { name: job.reducerName, onSchedule: fire }, + { arg: fire.rowType }, + t.unit(), + (ctx: CronProcedureCtx, { arg }: { arg: FireRow }) => { + executeProcedure(ctx, core, job, arg, handler); + return {}; } ); - job.fire = fire; - tables[job.fireAccessor] = asTableDefinition(fire); + }, + }; + metadata.set(handle, { + handle, + argsType: 'args' in opts ? opts.args : t.unit(), + hasArgs, + fireTableName: `${jobName}_fire`, + fireAccessor: toCamelCase(`${jobName}_fire`), + reducerName: `${jobName}_cron`, + fire: undefined, + core: undefined, + registration: undefined, + }); + return handle; +} + +/** Create the cron tables for `config.jobs` and the functions that manage them. */ +export function client( + config: Config +): CronClient { + const { jobs } = config; + if (jobs.length === 0) throw new Error(errors.noJobs); + const historyCap = normalizeHistoryCap(config.historyCap); + const isPublic = config.publicTables ?? false; + const reconcileEverySeconds = normalizeReconcileEverySeconds( + config.reconcileEverySeconds + ); + + const jobsByName = new Map(); + const argumentTypes: VariantsObj = {}; + 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(`${errors.duplicateJob}:${handle.jobName}`); + } + if (job.core) { + throw new Error(`${errors.jobAlreadyWired}:${handle.jobName}`); + } + if (usedAccessors.has(job.fireAccessor)) { + throw new Error(`${errors.tableKeyCollision}:${job.fireAccessor}`); + } + usedAccessors.add(job.fireAccessor); + jobsByName.set(handle.jobName, job); + argumentTypes[handle.jobName] = job.argsType; + } + + const tables: Record = { + cronJob: cronJobTable(argumentTypes), + cronRun: cronRunTable(isPublic), + }; + const reconcileTick = + reconcileEverySeconds === undefined + ? undefined + : cronReconcileTickTable(isPublic); + if (reconcileTick) tables.cronReconcileTick = reconcileTick; + for (const job of jobsByName.values()) { + job.fire = cronFireTable(job.fireTableName, isPublic); + tables[job.fireAccessor] = job.fire; + } + + const core: Core = { + jobs: jobsByName, + historyCap, + reconcileEverySeconds, + reconcileTick, + reconcileRegistered: false, + publicViewsRegistered: false, + }; + for (const job of jobsByName.values()) job.core = core; + + function jobInThisClient(handle: CronJobReference): JobMetadata { + const job = requireMetadata(handle); + if (job.core !== core) throw new Error(errors.foreignJobHandle); + return job; + } + + function reconcileReducer(spacetimedb: CronSchema) { + if (core.reconcileRegistered) { + throw new Error(errors.reconcileReducerAlreadyRegistered); + } + const tick = core.reconcileTick; + if (tick === undefined) { + throw new Error( + `${errors.reconcileNotConfigured}:set client({ reconcileEverySeconds })` + ); } + requireRegisteredHandlers(core); + core.reconcileRegistered = true; + return spacetimedb.reducer( + { name: RECONCILE_REDUCER_NAME, onSchedule: tick }, + { arg: tick.rowType }, + (ctx: CronTx) => { + requireDatabaseCaller(ctx); + reconcileLostFires(ctx, core); + } + ); + } - 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 publicViews(spacetimedb: CronSchema): CronPublicViews { + if (core.publicViewsRegistered) { + throw new Error(errors.publicViewsAlreadyRegistered); + } + core.publicViewsRegistered = true; + const jobsView = spacetimedb.anonymousView( + { name: 'cron_jobs', public: true }, + t.array(cronJobView), + (ctx: { db: { cronJob: { iter(): Iterable } } }) => + [...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 }; } - function schedule( - rawCtx: Ctx, + function schedule( + ctx: CronTx, handle: CronJobReference, spec: ScheduleSpec, opts?: RuntimeScheduleOpts ): void { - const ctx = asTransactionContext(rawCtx); - const job = requireMetadata(handle); - const core = requireCore(handle); + const job = jobInThisClient(handle); requireRegisteredHandlers(core); let normalized; let maxFailures: number; @@ -1079,7 +857,9 @@ export function spacetimeCron(sdk: CronSdk): CronApi { maxFailures = normalizeMaxFailures(opts?.maxFailures); args = normalizeJobArgs(handle.jobName, job.hasArgs, opts); } catch (error) { - throwInputError(error); + throw error instanceof CronInputError + ? new SenderError(error.message) + : error; } ensureReconcileTick(ctx, core); @@ -1089,10 +869,13 @@ export function spacetimeCron(sdk: CronSdk): CronApi { const generation = (existing?.generation ?? 0n) + 1n; disarmFire(ctx, job); + // The stored enum type is built from every job, so its static type keeps + // only the tag. + const taggedArgs = { tag: handle.jobName, value: args }; let row: JobRow = { name: handle.jobName, schedule: normalized.schedule, - args: { tag: handle.jobName, value: args }, + args: taggedArgs, enabled: true, maxFailures, consecutiveFailures: 0, @@ -1107,16 +890,14 @@ export function spacetimeCron(sdk: CronSdk): CronApi { const nextRunAt = insertFire(ctx, job, row, normalized.firstAt); if (!nextRunAt) { - throw new SenderError('cron.unsatisfiable_expression'); + throw new SenderError(errors.unsatisfiableExpression); } 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); + function unschedule(ctx: CronTx, handle: CronJobReference): void { + const job = jobInThisClient(handle); requireRegisteredHandlers(core); ensureReconcileTick(ctx, core); reconcileLostFires(ctx, core); @@ -1133,5 +914,12 @@ export function spacetimeCron(sdk: CronSdk): CronApi { }); } - return { cronTable, createCron, schedule, unschedule }; + return { + // The keys were derived from config.jobs exactly as CronTables derives them. + tables: tables as CronTables, + reconcileReducer, + publicViews, + schedule, + unschedule, + }; } diff --git a/spacetime-cron-ts/src/errors.ts b/spacetime-cron-ts/src/errors.ts new file mode 100644 index 00000000000..91a43cfcb00 --- /dev/null +++ b/spacetime-cron-ts/src/errors.ts @@ -0,0 +1,36 @@ +/** Codes thrown by cron. Some are followed by `:` and detail text. */ +export const errors = { + notAuthorized: 'cron.not_authorized', + foreignJobHandle: 'cron.foreign_job_handle', + notWired: 'cron.not_wired', + noJobs: 'cron.no_jobs', + duplicateJob: 'cron.duplicate_job', + jobAlreadyWired: 'cron.job_already_wired', + tableKeyCollision: 'cron.table_key_collision', + missingTable: 'cron.missing_table', + missingHandlers: 'cron.missing_handlers', + handlerAlreadyRegistered: 'cron.handler_already_registered', + reconcileNotConfigured: 'cron.reconcile_not_configured', + reconcileReducerNotRegistered: 'cron.reconcile_reducer_not_registered', + reconcileReducerAlreadyRegistered: + 'cron.reconcile_reducer_already_registered', + publicViewsAlreadyRegistered: 'cron.public_views_already_registered', + asyncReducerHandler: 'cron.async_reducer_handler', + asyncProcedureHandler: 'cron.async_procedure_handler', + invalidProcedureRecovery: 'cron.invalid_procedure_recovery', + invalidJobName: 'cron.invalid_job_name', + invalidHistoryCap: 'cron.invalid_history_cap', + invalidReconcileInterval: 'cron.invalid_reconcile_interval', + invalidMaxFailures: 'cron.invalid_max_failures', + invalidInterval: 'cron.invalid_interval', + invalidExpression: 'cron.invalid_expression', + invalidTimezone: 'cron.invalid_timezone', + unsatisfiableExpression: 'cron.unsatisfiable_expression', + missingArgs: 'cron.missing_args', + unexpectedArgs: 'cron.unexpected_args', + // Stored as a job's disabled reason. + invalidScheduleState: 'cron.invalid_schedule_state', + invalidArgsState: 'cron.invalid_args_state', + invalidTrigger: 'cron.invalid_trigger', + noFutureOccurrence: 'cron.no_future_occurrence', +} as const; diff --git a/spacetime-cron-ts/src/index.ts b/spacetime-cron-ts/src/index.ts index 2ad33bc32f1..a919a2fe0e8 100644 --- a/spacetime-cron-ts/src/index.ts +++ b/spacetime-cron-ts/src/index.ts @@ -1,21 +1,22 @@ -export { spacetimeCron } from './cron'; +export { client, cronTable } from './cron'; +export { errors } from './errors'; export type { - CreateCronOpts, - CronApi, CronArgsBuilder, - CronCore, - CronCorePublicViews, + CronClient, + CronConfig, + CronFunctionExport, + CronHandler, CronInvocation, CronJobHandle, CronJobReference, - CronProcedureHandler, - CronReducerHandler, + CronProcedureCtx, + CronPublicViews, CronSchedule, CronSchema, - CronSdk, CronTableOpts, CronTableWithArgsOpts, - CronTimestamp, + CronTables, + CronTx, ScheduleOpts, ScheduleSpec, } from './types'; diff --git a/spacetime-cron-ts/src/schedule.ts b/spacetime-cron-ts/src/schedule.ts index c4ba7db575c..9c3a9467538 100644 --- a/spacetime-cron-ts/src/schedule.ts +++ b/spacetime-cron-ts/src/schedule.ts @@ -5,6 +5,7 @@ import { nextFireAfter, parseCronExpression, } from './parser'; +import { errors } from './errors'; import type { CronSchedule, ScheduleSpec } from './types'; export const ONE_SECOND_MICROS = 1_000_000n; @@ -36,7 +37,7 @@ export function normalizeJobName(name: string): string { !JOB_NAME_PATTERN.test(normalized) ) { throw new CronInputError( - 'cron.invalid_job_name:use 1-48 lowercase snake_case characters' + `${errors.invalidJobName}:use 1-48 lowercase snake_case characters` ); } return normalized; @@ -46,7 +47,7 @@ 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}` + `${errors.invalidHistoryCap}:must be an integer between 0 and ${MAX_HISTORY_CAP}` ); } return cap; @@ -62,7 +63,7 @@ export function normalizeReconcileEverySeconds( value > MAX_INTERVAL_SECONDS ) { throw new CronInputError( - `cron.invalid_reconcile_interval:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` + `${errors.invalidReconcileInterval}:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` ); } return value; @@ -76,7 +77,7 @@ export function normalizeMaxFailures(value: number | undefined): number { failures > MAX_FAILURES ) { throw new CronInputError( - `cron.invalid_max_failures:must be an integer between 0 and ${MAX_FAILURES}` + `${errors.invalidMaxFailures}:must be an integer between 0 and ${MAX_FAILURES}` ); } return failures; @@ -89,10 +90,10 @@ export function normalizeJobArgs( ): unknown { const supplied = Object.prototype.hasOwnProperty.call(opts ?? {}, 'args'); if (hasArgs && !supplied) { - throw new CronInputError(`cron.missing_args:${jobName}`); + throw new CronInputError(`${errors.missingArgs}:${jobName}`); } if (!hasArgs && supplied) { - throw new CronInputError(`cron.unexpected_args:${jobName}`); + throw new CronInputError(`${errors.unexpectedArgs}:${jobName}`); } return hasArgs ? opts?.args : {}; } @@ -110,7 +111,7 @@ export function normalizeSchedule( seconds > MAX_INTERVAL_SECONDS ) { throw new CronInputError( - `cron.invalid_interval:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` + `${errors.invalidInterval}:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` ); } return { @@ -122,16 +123,16 @@ export function normalizeSchedule( const expression = spec.trim(); const timezone = (opts?.timezone ?? 'UTC').trim() || 'UTC'; if (expression.length === 0) { - throw new CronInputError('cron.invalid_expression:empty'); + throw new CronInputError(`${errors.invalidExpression}:empty`); } if (expression.length > MAX_CRON_EXPRESSION_LENGTH) { - throw new CronInputError('cron.invalid_expression:too_long'); + throw new CronInputError(`${errors.invalidExpression}:too_long`); } if (timezone.length > MAX_TIMEZONE_LENGTH) { - throw new CronInputError('cron.invalid_timezone:too_long'); + throw new CronInputError(`${errors.invalidTimezone}:too_long`); } if (!isValidTimezone(timezone)) { - throw new CronInputError(`cron.invalid_timezone:${timezone}`); + throw new CronInputError(`${errors.invalidTimezone}:${timezone}`); } let firstAt: bigint | undefined; @@ -143,10 +144,10 @@ export function normalizeSchedule( ); } catch (error) { const detail = error instanceof Error ? error.message : String(error); - throw new CronInputError(`cron.invalid_expression:${detail}`); + throw new CronInputError(`${errors.invalidExpression}:${detail}`); } if (firstAt === undefined) { - throw new CronInputError('cron.unsatisfiable_expression'); + throw new CronInputError(errors.unsatisfiableExpression); } return { schedule: { tag: 'cron', value: { expression, timezone } }, diff --git a/spacetime-cron-ts/src/tables.ts b/spacetime-cron-ts/src/tables.ts new file mode 100644 index 00000000000..317c45e4d5e --- /dev/null +++ b/spacetime-cron-ts/src/tables.ts @@ -0,0 +1,153 @@ +import type { Identity, Timestamp } from 'spacetimedb'; +import { t, table, type Infer, type VariantsObj } from 'spacetimedb/server'; + +const cronSchedule = t.enum('CronSchedule', { + cron: t.object('CronSpec', { + expression: t.string(), + timezone: t.string(), + }), + every: t.object('EverySpec', { + seconds: t.u32(), + }), +}); + +const cronRunStatus = t.enum('CronRunStatus', ['Ok', 'Failed']); + +const cronFireRecovery = t.object('CronFireRecovery', { + sequence: t.u64(), + scheduledFor: t.timestamp(), + error: t.string(), +}); + +/** Public projection of `cron_job` without typed arguments. */ +export const cronJobView = t.row('CronJobView', { + name: t.string().primaryKey(), + schedule: 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 function cronJobTable(args: VariantsObj) { + return table( + { name: 'cron_job', public: false }, + { + name: t.string().primaryKey(), + schedule: cronSchedule, + args: t.enum('CronJobArgsValue', args), + 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 function cronRunTable(isPublic: boolean) { + return 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: cronRunStatus, + error: t.option(t.string()), + } + ); +} + +export function cronFireTable(name: string, isPublic: boolean) { + return table( + { name, 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(cronFireRecovery), + } + ); +} + +export function cronReconcileTickTable(isPublic: boolean) { + return table( + { name: 'cron_reconcile_tick', public: isPublic }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + key: t.string().unique(), + } + ); +} + +export type CronJobTableDef = ReturnType; +export type CronRunTableDef = ReturnType; +export type CronFireTableDef = ReturnType; +export type CronReconcileTickTableDef = ReturnType< + typeof cronReconcileTickTable +>; + +export type JobRow = Infer; +export type RunRow = Infer; +export type FireRow = Infer; +export type ReconcileTickRow = Infer; + +/** The cron tables of a host reducer or transaction context. */ +export interface CronDb { + readonly cronJob: { + readonly name: { + find(name: string): JobRow | null; + update(row: JobRow): JobRow; + }; + insert(row: JobRow): JobRow; + }; + readonly cronRun: { + readonly invocationId: { find(id: string): RunRow | null }; + readonly jobName: { filter(jobName: string): Iterable }; + insert(row: RunRow): RunRow; + delete(row: RunRow): boolean; + }; + readonly cronReconcileTick?: { + readonly key: { find(key: string): ReconcileTickRow | null }; + insert(row: ReconcileTickRow): ReconcileTickRow; + }; + /** Per-job fire tables, keyed by `Fire`. */ + readonly [accessor: string]: unknown; +} + +/** The parts of a host fire table that cron reads and writes. */ +export interface CronFireTable { + readonly jobName: { find(jobName: string): FireRow | null }; + readonly scheduledId: { find(scheduledId: bigint): FireRow | null }; + insert(row: FireRow): FireRow; + delete(row: FireRow): boolean; +} + +/** A host reducer context whose schema includes `cron.tables`. */ +export interface CronTx { + readonly sender: Identity; + readonly databaseIdentity: Identity; + readonly timestamp: Timestamp; + readonly db: CronDb; +} + +/** A host procedure context whose schema includes `cron.tables`. */ +export interface CronProcedureCtx { + readonly sender: Identity; + readonly databaseIdentity: Identity; + readonly timestamp: Timestamp; + withTx(body: (tx: CronTx) => T): T; +} diff --git a/spacetime-cron-ts/src/types.ts b/spacetime-cron-ts/src/types.ts index 09edb01812e..0755d35bbee 100644 --- a/spacetime-cron-ts/src/types.ts +++ b/spacetime-cron-ts/src/types.ts @@ -1,14 +1,20 @@ import type { Timestamp } from 'spacetimedb'; import type { - Infer, ModuleExport, - ScheduleAt, - SenderError, - t, - table, toCamelCase, VariantsObj, } from 'spacetimedb/server'; +import type { + CronFireTableDef, + CronJobTableDef, + CronProcedureCtx, + CronReconcileTickTableDef, + CronRunTableDef, + CronTx, + FireRow, +} from './tables'; + +export type { CronProcedureCtx, CronTx } from './tables'; export type CronSchedule = | { tag: 'cron'; value: { expression: string; timezone: string } } @@ -44,7 +50,9 @@ export interface CronTableWithArgsOpts< args: ArgsBuilder; } -export interface CreateCronOpts { +export interface CronConfig { + /** Every job handle in the module, each created by `cronTable()`. */ + jobs: readonly CronJobReference[]; /** Completed run records retained per job. Defaults to `5`. */ historyCap?: number; /** Expose trigger and run tables to subscriptions. Defaults to `false`. */ @@ -56,14 +64,6 @@ export interface CreateCronOpts { 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. */ @@ -72,26 +72,28 @@ export interface CronInvocation { readonly generation: bigint; readonly sequence: bigint; /** Logical calendar occurrence or interval fire time. */ - readonly scheduledFor: CronTimestamp; + readonly scheduledFor: Timestamp; } -export type CronReducerHandler = [Args] extends [ - undefined, -] - ? (ctx: Ctx, invocation: CronInvocation) => void - : (ctx: Ctx, args: Args, invocation: CronInvocation) => void; - -export type CronProcedureHandler = [Args] extends [ - undefined, -] +export type CronHandler = [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; +/** A scheduled reducer or procedure registered for one job. */ +export type CronFunctionExport = ModuleExport & + ((ctx: Ctx, args: { arg: FireRow }) => unknown); + +/** + * The host schema returned by `schema()`. Handler contexts are inferred from + * its reducer and procedure exports. + */ +export interface CronSchema< + Tx extends CronTx = CronTx, + Proc extends CronProcedureCtx = CronProcedureCtx, +> { + reducer(...args: unknown[]): CronFunctionExport; + procedure(...args: unknown[]): CronFunctionExport; + anonymousView(...args: unknown[]): ModuleExport; } export interface CronJobReference { @@ -100,59 +102,51 @@ export interface CronJobReference { export interface CronJobHandle extends CronJobReference { - cronReducer( - spacetimedb: CronSchema, - handler: CronReducerHandler - ): ModuleExport; - cronProcedure( - spacetimedb: CronSchema, - handler: CronProcedureHandler - ): ModuleExport; + cronReducer( + spacetimedb: CronSchema, + handler: CronHandler + ): CronFunctionExport; + cronProcedure( + spacetimedb: CronSchema, + handler: CronHandler + ): CronFunctionExport; } -export interface CronCorePublicViews { +type FireAccessor = ReturnType< + typeof toCamelCase<`${Name}_fire`> +>; + +/** The tables to spread into the host's `schema()` call. */ +export type CronTables = { + readonly cronJob: CronJobTableDef; + readonly cronRun: CronRunTableDef; +} & { + readonly [Job in Config['jobs'][number] as FireAccessor< + Job['jobName'] + >]: CronFireTableDef; +} & (Config extends { reconcileEverySeconds: number } + ? { readonly cronReconcileTick: CronReconcileTickTableDef } + : unknown); + +export interface CronPublicViews { /** Sanitized job state. Typed application arguments remain private. */ readonly jobs: ModuleExport; } -export interface CronCore { - /** Spread into the consumer's `schema()` call. */ - readonly tables: Record; +export interface CronClient { + /** Spread into the host's `schema()` call. */ + readonly tables: CronTables; /** Register and export the optional lost-trigger reconciliation sweep. */ - reconcileReducer(spacetimedb: CronSchema): ModuleExport; + 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; + publicViews( + spacetimedb: CronSchema + ): CronPublicViews; /** Create or replace a job schedule and arm its first trigger. */ - schedule( - ctx: Ctx, + schedule( + ctx: CronTx, job: CronJobHandle, spec: ScheduleSpec, ...options: [Args] extends [undefined] @@ -160,5 +154,5 @@ export interface CronApi { : [opts: ScheduleOpts>] ): void; /** Disable a job and remove its pending trigger. */ - unschedule(ctx: Ctx, job: CronJobReference): void; + unschedule(ctx: CronTx, job: CronJobReference): void; } diff --git a/spacetime-cron-ts/tsconfig.json b/spacetime-cron-ts/tsconfig.json index b2b4ecdcdda..77da6c09f65 100644 --- a/spacetime-cron-ts/tsconfig.json +++ b/spacetime-cron-ts/tsconfig.json @@ -7,8 +7,7 @@ "noEmit": true, "skipLibCheck": true, "moduleResolution": "Bundler", - "isolatedModules": true, - "allowImportingTsExtensions": true + "isolatedModules": true }, "include": ["src/**/*.ts", "scripts/**/*.ts"], "exclude": ["node_modules"] From 812c0d24e85d752c431910ebcac0dfdd9cf7b146 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 11:59:52 -0400 Subject: [PATCH 15/32] Register retry handlers after schema with typed contexts client({ tasks }) declares each task's argument type before schema(). retry.retryReducer(spacetimedb, handlers) registers the scheduled reducer afterward, so every handler receives the host's reducer context and its task's arguments with their real types, and the host schema must include retry.tables. retryHandler is removed along with the fixture's context cast. --- spacetime-retry-ts/README.md | 47 ++- spacetime-retry-ts/scripts/test.ts | 73 +++-- spacetime-retry-ts/spacetimedb/src/index.ts | 82 ++---- spacetime-retry-ts/src/handler.ts | 24 -- spacetime-retry-ts/src/index.ts | 15 +- spacetime-retry-ts/src/submodule.ts | 304 +++++++++++--------- 6 files changed, 271 insertions(+), 274 deletions(-) diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md index d2e921af709..ae1ccc7bc25 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -23,23 +23,19 @@ For the install-to-publish workflow, see ### Integrate into an application -The task variants and handlers belong to the host, so `client()` runs when the -module loads, before `schema()`. The example below is a module-definition -skeleton: replace `sendReceipt` with an idempotent application handler. +Declare each task's argument type in `client()` when the module loads, before +`schema()`. Register the handlers with `retry.retryReducer()` after +`schema()`, so each handler receives the host's typed reducer context and its +task's typed arguments. The example below is a module-definition skeleton: +replace `sendReceipt` with an idempotent application function. ```ts import { schema, t } from 'spacetimedb/server'; -import { client, retryFailed, retryHandler, retryOk } from '@spacetimedb/retry'; +import { client, retryFailed, retryOk } from '@spacetimedb/retry'; const retry = client({ - handlers: { - sendReceipt: retryHandler( - t.object('SendReceiptArgs', { orderId: t.u64() }), - (ctx, { orderId }) => { - const result = sendReceipt(ctx, orderId); - return result.sent ? retryOk() : retryFailed(result.error); - } - ), + tasks: { + sendReceipt: t.object('SendReceiptArgs', { orderId: t.u64() }), }, }); @@ -48,11 +44,12 @@ export default db; export const init = db.init(ctx => retry.install(ctx)); -export const retryFire = db.reducer( - { onSchedule: retry.tables.retryTask }, - { arg: retry.tables.retryTask.rowType }, - retry.reducers.retryFire -); +export const retryFire = retry.retryReducer(db, { + sendReceipt(ctx, { orderId }) { + const result = sendReceipt(ctx, orderId); + return result.sent ? retryOk() : retryFailed(result.error); + }, +}); export const submitRetryTask = db.reducer( retry.reducers.submitRetryTask.params, @@ -60,9 +57,8 @@ export const submitRetryTask = db.reducer( ); ``` -Register the scheduled reducer after `schema()` so it can reference the -scheduled table. Handlers receive the host's reducer context as `unknown` -because it is defined after the handlers. +`retryReducer` requires a handler for every task. Registration fails to +compile if the schema does not include `retry.tables`. Submit tagged arguments with an attempt cap and base backoff. The first attempt is scheduled immediately; subsequent delays are `backoffSecs * 2^attempt`. @@ -78,8 +74,11 @@ view returns these attempts newest first. ## API -- `client({ handlers })` returns `tables`, `install`, `submit`, +- `client({ tasks })` returns `tables`, `retryReducer`, `install`, `submit`, `requireAdmin`, `views`, and `reducers`. +- `retryReducer(schema, handlers)` registers the scheduled reducer that runs + attempts. Export its result. Each handler returns `retryOk()` or + `retryFailed(error)`. - `install(ctx)` seeds the publishing identity as the initial admin. Call it from the host's `init` reducer. - `submit(ctx, task)` validates a task and schedules its first attempt without @@ -88,8 +87,6 @@ view returns these attempts newest first. `reducers.removeRetryAdminIdentity` require a Retry admin. - `views.retryTasksAdmin` and `views.retryHistoryAdmin` return up to 1,000 pending tasks and attempts, newest first, to Retry admins. -- `retryHandler(args, run)` pairs a SpacetimeDB type builder with a task - handler. The handler returns `retryOk()` or `retryFailed(error)`. - `errors` holds the `retry.*` codes thrown by these operations. The generated client can submit a task when the host exports @@ -126,8 +123,8 @@ Operational screens can subscribe to the admin task and history views. Package entrypoints: -- `@spacetimedb/retry` exports `client`, `errors`, and the handler and result - helpers. +- `@spacetimedb/retry` exports `client`, `errors`, `retryOk`, `retryFailed`, + and the related types. - `@spacetimedb/retry/submodule` exports `client` and `errors`. ## Testing diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts index f400b1d26e1..d04641b4b51 100644 --- a/spacetime-retry-ts/scripts/test.ts +++ b/spacetime-retry-ts/scripts/test.ts @@ -1,32 +1,47 @@ import * as assert from 'node:assert/strict'; import { Identity, Timestamp } from 'spacetimedb'; -import { ScheduleAt, t } from 'spacetimedb/server'; -import { client, errors, retryFailed, retryHandler, retryOk } from '../src'; +import { ScheduleAt, schema, t } from 'spacetimedb/server'; +import { + client, + errors, + retryFailed, + retryOk, + type RetryCtx, + type RetryTaskRow as Task, +} from '../src'; const calls: string[] = []; +// One argument type may back several tasks. const sharedArgs = t.object('TestArgs', { value: t.string() }); const retry = client({ - handlers: { - throws: retryHandler(t.unit(), () => { - throw new Error('x'.repeat(3000)); - }), - fails: retryHandler(t.unit(), () => retryFailed('unavailable')), - succeeds: retryHandler(t.unit(), () => retryOk()), - // One argument builder may back several handlers. - first: retryHandler(sharedArgs, (_ctx, args) => { - calls.push(`first:${args.value}`); - return retryOk(); - }), - second: retryHandler(sharedArgs, (_ctx, args) => { - calls.push(`second:${args.value}`); - return retryOk(); - }), + tasks: { + throws: t.unit(), + fails: t.unit(), + succeeds: t.unit(), + first: sharedArgs, + second: sharedArgs, }, }); +const retryFire = retry.retryReducer(schema({ ...retry.tables }), { + throws() { + throw new Error('x'.repeat(3000)); + }, + fails: () => retryFailed('unavailable'), + succeeds: () => retryOk(), + first(_ctx, args) { + calls.push(`first:${args.value}`); + return retryOk(); + }, + second(_ctx, args) { + calls.push(`second:${args.value}`); + return retryOk(); + }, +}); +// The mock context implements only the retry tables, not a full reducer +// context. +const fire = (arg: Task) => retryFire(ctx as never, { arg }); -type Task = Parameters[1]['arg']; type History = ReturnType[number]; -type Ctx = Parameters[0]; const admin = Identity.zero(); const stranger = new Identity(1n); @@ -47,7 +62,7 @@ const byRanAt = () => ) .values(); -const ctx: Ctx = { +const ctx: RetryCtx = { get sender() { return sender; }, @@ -136,8 +151,8 @@ retry.submit(ctx, { backoffSecs: 1, }); sender = admin; -retry.reducers.retryFire(ctx, { arg: tasks.get(1n)! }); -retry.reducers.retryFire(ctx, { arg: tasks.get(2n)! }); +fire(tasks.get(1n)!); +fire(tasks.get(2n)!); assert.deepEqual(calls, ['first:payload', 'second:b']); // Failures back off exponentially, then give up. @@ -153,23 +168,23 @@ const task: Task = { }; history.clear(); nextHistoryId = 0n; -retry.reducers.retryFire(ctx, { arg: task }); +fire(task); assert.equal(history.get(1n)?.status.tag, 'Failed'); assert.equal(history.get(1n)?.error?.length, 2048); const [second] = tasks.values(); assert.equal(second.attempt, 1); assert.deepEqual(second.scheduledAt, ScheduleAt.time(now + 2_000_000n)); -retry.reducers.retryFire(ctx, { arg: second }); +fire(second); const third = [...tasks.values()][1]; assert.equal(third.attempt, 2); assert.deepEqual(third.scheduledAt, ScheduleAt.time(now + 4_000_000n)); -retry.reducers.retryFire(ctx, { arg: third }); +fire(third); assert.equal(history.get(3n)?.status.tag, 'GaveUp'); assert.equal(tasks.size, 2); -retry.reducers.retryFire(ctx, { arg: { ...task, args: { tag: 'fails' } } }); +fire({ ...task, args: { tag: 'fails' } }); assert.equal(history.get(4n)?.error, 'unavailable'); -retry.reducers.retryFire(ctx, { arg: { ...task, args: { tag: 'toString' } } }); +fire({ ...task, args: { tag: 'toString' } }); assert.equal(history.get(5n)?.error, `${errors.unknownHandler}:toString`); assert.equal(tasks.size, 4); @@ -182,9 +197,7 @@ assert.deepEqual( // History keeps the latest 1,000 attempts. for (let i = 0; i < 1000; i++) { now += 1n; - retry.reducers.retryFire(ctx, { - arg: { ...task, args: { tag: 'succeeds' } }, - }); + fire({ ...task, args: { tag: 'succeeds' } }); } assert.equal(tasks.size, 4); assert.equal(history.size, 1000); diff --git a/spacetime-retry-ts/spacetimedb/src/index.ts b/spacetime-retry-ts/spacetimedb/src/index.ts index 7f3504169d4..ae153b03c3d 100644 --- a/spacetime-retry-ts/spacetimedb/src/index.ts +++ b/spacetime-retry-ts/spacetimedb/src/index.ts @@ -1,56 +1,15 @@ import { schema, table, t } from 'spacetimedb/server'; -import { - client, - retryFailed, - retryHandler, - retryOk, - type RetryResult, -} from '@spacetimedb/retry'; +import { client, retryFailed, retryOk } 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 retry = client({ + tasks: { + flaky: t.object('FlakyArgs', { + taskName: t.string(), + succeedAtAttempt: t.u8(), + throwOnFailure: t.bool(), + }), + }, }); - -const retry = client({ handlers: { flaky } }); const { retryTask, retryHistory, retryAdminIdentity } = retry.tables; const retryMetric = table( @@ -87,11 +46,24 @@ export const init = spacetimedb.init(ctx => { retry.install(ctx); }); -export const retryFire = spacetimedb.reducer( - { onSchedule: retryTask }, - { arg: retryTask.rowType }, - retry.reducers.retryFire -); +export const retryFire = retry.retryReducer(spacetimedb, { + flaky(ctx, args) { + const task = ctx.db.retryTask.name.filter(args.taskName).next().value; + const attempt = task?.attempt ?? 0; + if (attempt < args.succeedAtAttempt) { + const message = `simulated failure at attempt ${attempt}`; + if (args.throwOnFailure) throw new Error(message); + return retryFailed(message); + } + ctx.db.retryMetric.insert({ + id: 0n, + name: `flaky-success-${args.taskName}`, + value: attempt, + recordedAt: ctx.timestamp, + }); + return retryOk(); + }, +}); export const submitRetryTask = spacetimedb.reducer( retry.reducers.submitRetryTask.params, diff --git a/spacetime-retry-ts/src/handler.ts b/spacetime-retry-ts/src/handler.ts index e066a0225bc..fcf089b4bd6 100644 --- a/spacetime-retry-ts/src/handler.ts +++ b/spacetime-retry-ts/src/handler.ts @@ -1,9 +1,3 @@ -import type { Infer, VariantsObj } from 'spacetimedb/server'; - -type ArgsBuilder = VariantsObj[string]; - -type IsUnit = [keyof T] extends [never] ? true : false; - export type RetryResult = { ok: true } | { ok: false; error: string }; export const retryOk = (): RetryResult => ({ ok: true }); @@ -11,21 +5,3 @@ export const retryFailed = (error: string): RetryResult => ({ ok: false, error, }); - -type RunFn = - IsUnit> extends true - ? (ctx: unknown) => RetryResult - : (ctx: unknown, args: Infer) => RetryResult; - -export type RetryHandler = { - readonly args: TB; - readonly run: RunFn; -}; - -/** Pair a task argument type with the function that runs one attempt. */ -export function retryHandler( - args: TB, - run: RunFn -): RetryHandler { - return { args, run }; -} diff --git a/spacetime-retry-ts/src/index.ts b/spacetime-retry-ts/src/index.ts index 522f5db3544..36e9c07c43c 100644 --- a/spacetime-retry-ts/src/index.ts +++ b/spacetime-retry-ts/src/index.ts @@ -1,14 +1,15 @@ -export { - retryFailed, - retryHandler, - retryOk, - type RetryHandler, - type RetryResult, -} from './handler'; +export { retryFailed, retryOk, type RetryResult } from './handler'; export { client, errors, type RetryArgs, type RetryConfig, + type RetryCtx, type RetryHandlers, + type RetryHistoryRow, + type RetryReducerExport, + type RetrySchema, + type RetryTaskRow, + type RetryTasks, + type RetryViewCtx, } from './submodule'; diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index d11477ddf31..b3b5db995e7 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -5,10 +5,12 @@ import { t, table, type Infer, + type ModuleExport, + type SumBuilder, type VariantsObj, } from 'spacetimedb/server'; import type { Identity, Timestamp } from 'spacetimedb'; -import { retryFailed, type RetryHandler, type RetryResult } from './handler'; +import { retryFailed, type RetryResult } from './handler'; const ONE_SECOND_MICROS = 1_000_000n; const MAX_ATTEMPTS = 10; @@ -27,117 +29,136 @@ export const errors = { unknownHandler: 'retry.unknown_handler', } as const; -export type RetryHandlers = Record; - -export interface RetryConfig { - /** Task variants keyed by tag. Each handler runs one attempt. */ - handlers: H; -} - -/** Tagged task arguments for the configured handlers. */ -export type RetryArgs = { - [K in keyof H & string]: H[K]['args'] extends ReturnType - ? { tag: K } - : { tag: K; value: Infer }; -}[keyof H & string]; - -/** Create the retry tables, reducers, and views from the host's handlers. */ -export function client({ - handlers, -}: RetryConfig) { - const variants: VariantsObj = {}; - for (const [tag, handler] of Object.entries(handlers)) { - variants[tag] = handler.args; - } - const retryArgs = t.enum('RetryArgs', variants); - - const retryTask = table( +function retryTaskTable(args: SumBuilder) { + return table( { name: 'retry_task', public: false }, { scheduledId: t.u64().primaryKey().autoInc(), scheduledAt: t.scheduleAt(), name: t.string().index(), - args: retryArgs, + args, attempt: t.u8(), maxAttempts: t.u8(), backoffSecs: t.u32(), } ); +} - const retryHistory = table( - { name: 'retry_history', public: false }, - { - id: t.u64().primaryKey().autoInc(), - taskName: t.string(), - attempt: t.u8(), - status: t.enum('RetryHistoryStatus', ['Ok', 'Failed', 'GaveUp']), - error: t.option(t.string()), - ranAt: t.timestamp().index(), - } - ); +const retryHistory = table( + { name: 'retry_history', public: false }, + { + id: t.u64().primaryKey().autoInc(), + taskName: t.string(), + attempt: t.u8(), + status: t.enum('RetryHistoryStatus', ['Ok', 'Failed', 'GaveUp']), + error: t.option(t.string()), + ranAt: t.timestamp().index(), + } +); - const retryAdminIdentity = table( - { name: 'retry_admin_identity', public: false }, - { - identity: t.identity().primaryKey(), - addedAt: t.timestamp(), - } - ); +const retryAdminIdentity = table( + { name: 'retry_admin_identity', public: false }, + { + identity: t.identity().primaryKey(), + addedAt: t.timestamp(), + } +); - type TaskRow = Infer; - type HistoryRow = Infer; - type AdminRow = Infer; - type TaskInput = Pick< - TaskRow, - 'name' | 'args' | 'maxAttempts' | 'backoffSecs' - >; +export type RetryTaskRow = Infer['rowType']>; +export type RetryHistoryRow = Infer; +type AdminRow = Infer; +type TaskInput = Pick< + RetryTaskRow, + 'name' | 'args' | 'maxAttempts' | 'backoffSecs' +>; - /** The parts of a host view context that retry reads. */ - interface RetryViewCtx { - readonly sender: Identity; - readonly db: { - readonly retryTask: { iter(): Iterable }; - readonly retryHistory: { - readonly ranAt: { - filter(range: Range): Iterable; - }; - }; - readonly retryAdminIdentity: { - readonly identity: { find(identity: Identity): AdminRow | null }; +/** The retry tables of a host view context. */ +export interface RetryViewCtx { + readonly sender: Identity; + readonly db: { + readonly retryTask: { iter(): Iterable }; + readonly retryHistory: { + readonly ranAt: { + filter(range: Range): Iterable; }; }; - } + readonly retryAdminIdentity: { + readonly identity: { find(identity: Identity): AdminRow | null }; + }; + }; +} - /** The parts of a host reducer context that retry reads and writes. */ - interface RetryCtx { - readonly sender: Identity; - readonly timestamp: Timestamp; - readonly db: { - readonly retryTask: { - iter(): Iterable; - readonly name: { - filter(name: string): IteratorObject; - }; - insert(row: TaskRow): TaskRow; +/** A host reducer context whose schema includes `retry.tables`. */ +export interface RetryCtx { + readonly sender: Identity; + readonly timestamp: Timestamp; + readonly db: { + readonly retryTask: { + iter(): Iterable; + readonly name: { + filter(name: string): IteratorObject; }; - readonly retryHistory: { - readonly ranAt: { - filter( - range: Range - ): IteratorObject; - }; - insert(row: HistoryRow): HistoryRow; - delete(row: HistoryRow): boolean; - count(): bigint; - }; - readonly retryAdminIdentity: { - readonly identity: { find(identity: Identity): AdminRow | null }; - insert(row: AdminRow): AdminRow; - delete(row: AdminRow): boolean; - count(): bigint; + insert(row: RetryTaskRow): RetryTaskRow; + }; + readonly retryHistory: { + readonly ranAt: { + filter( + range: Range + ): IteratorObject; }; + insert(row: RetryHistoryRow): RetryHistoryRow; + delete(row: RetryHistoryRow): boolean; + count(): bigint; }; - } + readonly retryAdminIdentity: { + readonly identity: { find(identity: Identity): AdminRow | null }; + insert(row: AdminRow): AdminRow; + delete(row: AdminRow): boolean; + count(): bigint; + }; + }; +} + +/** Task argument types keyed by task tag. */ +export type RetryTasks = VariantsObj; + +export interface RetryConfig { + tasks: Tasks; +} + +/** Tagged task arguments for the configured tasks. */ +export type RetryArgs = { + [K in keyof Tasks & string]: Tasks[K] extends ReturnType + ? { tag: K } + : { tag: K; value: Infer }; +}[keyof Tasks & string]; + +/** One handler per task tag. Each call runs one attempt. */ +export type RetryHandlers = { + [K in keyof Tasks & string]: (ctx: Tx, args: Infer) => RetryResult; +}; + +/** The scheduled reducer that runs attempts. */ +export type RetryReducerExport = ModuleExport & + ((ctx: Tx, args: { arg: RetryTaskRow }) => unknown); + +/** + * The host schema returned by `schema()`. Handler contexts are inferred from + * its reducer exports. + */ +export interface RetrySchema { + reducer(...args: unknown[]): RetryReducerExport; +} + +type InternalHandler = (...args: unknown[]) => RetryResult; + +/** Create the retry tables and the functions that manage them. */ +export function client({ + tasks, +}: RetryConfig) { + const variants: VariantsObj = tasks; + const retryArgs = t.enum('RetryArgs', variants); + const retryTask = retryTaskTable(retryArgs); function isAdmin(ctx: RetryViewCtx): boolean { return ctx.db.retryAdminIdentity.identity.find(ctx.sender) != null; @@ -153,11 +174,6 @@ export function client({ } } - /** Call from the host's init reducer to seed the publishing identity as admin. */ - function install(ctx: RetryCtx): void { - addAdmin(ctx, ctx.sender); - } - function submitTask(ctx: RetryCtx, task: TaskInput): void { if (task.name.length === 0 || task.name.length > MAX_TASK_NAME_LENGTH) { throw new SenderError(errors.invalidTaskName); @@ -187,18 +203,18 @@ export function client({ }); } - function dispatch(ctx: RetryCtx, args: TaskRow['args']): RetryResult { - if (!Object.prototype.hasOwnProperty.call(handlers, args.tag)) { - throw new Error(`${errors.unknownHandler}:${args.tag}`); - } - const value = 'value' in args ? args.value : undefined; - return handlers[args.tag].run(ctx, value); - } - - function retryFire(ctx: RetryCtx, { arg }: { arg: TaskRow }): void { + function runAttempt( + handlers: Record, + ctx: RetryCtx, + arg: RetryTaskRow + ): void { let result: RetryResult; try { - result = dispatch(ctx, arg.args); + const { tag } = arg.args; + if (!Object.prototype.hasOwnProperty.call(handlers, tag)) { + throw new Error(`${errors.unknownHandler}:${tag}`); + } + result = handlers[tag](ctx, 'value' in arg.args ? arg.args.value : {}); } catch (error) { // A caught exception does not roll back the handler's earlier writes. result = retryFailed( @@ -216,7 +232,7 @@ export function client({ error: result.ok ? undefined : result.error.slice(0, MAX_ERROR_LENGTH), ranAt: ctx.timestamp, }); - // Each fire adds one row, so removing the oldest keeps the bound. + // Each attempt adds one row, so removing the oldest keeps the bound. if (history.count() > MAX_ROWS) { const oldest = history.ranAt.filter(new Range()).next().value; if (oldest) history.delete(oldest); @@ -233,42 +249,64 @@ export function client({ }); } - /** The latest pending tasks, newest first. */ - function retryTasksAdmin(ctx: RetryViewCtx): TaskRow[] { - if (!isAdmin(ctx)) return []; - return [...ctx.db.retryTask.iter()] - .sort((a, b) => - a.scheduledId > b.scheduledId - ? -1 - : a.scheduledId < b.scheduledId - ? 1 - : 0 - ) - .slice(0, MAX_ROWS); - } - - /** Retained attempt history, newest first. */ - function retryHistoryAdmin(ctx: RetryViewCtx): HistoryRow[] { - if (!isAdmin(ctx)) return []; - return [ - ...ctx.db.retryHistory.ranAt.filter(new Range()), - ].reverse(); + /** + * Register the scheduled reducer that runs attempts. Call after `schema()` + * and export the result. + */ + function retryReducer( + spacetimedb: RetrySchema, + handlers: RetryHandlers + ): RetryReducerExport { + // Each stored task pairs a tag with a value of that tag's argument type, + // so the handler for the tag accepts the value. + const byTag = handlers as Record; + return spacetimedb.reducer( + { onSchedule: retryTask }, + { arg: retryTask.rowType }, + (ctx: Tx, { arg }: { arg: RetryTaskRow }) => { + runAttempt(byTag, ctx, arg); + } + ); } return { tables: { retryTask, retryHistory, retryAdminIdentity }, - install, + retryReducer, + /** Call from the host's init reducer to seed the publishing identity as admin. */ + install(ctx: RetryCtx): void { + addAdmin(ctx, ctx.sender); + }, /** Validate and schedule a task's first attempt. The caller authorizes. */ submit( ctx: RetryCtx, - task: Omit & { args: RetryArgs } + task: Omit & { args: RetryArgs } ): void { submitTask(ctx, task); }, requireAdmin, - views: { retryTasksAdmin, retryHistoryAdmin }, + views: { + /** The latest pending tasks, newest first. */ + retryTasksAdmin(ctx: RetryViewCtx): RetryTaskRow[] { + if (!isAdmin(ctx)) return []; + return [...ctx.db.retryTask.iter()] + .sort((a, b) => + a.scheduledId > b.scheduledId + ? -1 + : a.scheduledId < b.scheduledId + ? 1 + : 0 + ) + .slice(0, MAX_ROWS); + }, + /** Retained attempt history, newest first. */ + retryHistoryAdmin(ctx: RetryViewCtx): RetryHistoryRow[] { + if (!isAdmin(ctx)) return []; + return [ + ...ctx.db.retryHistory.ranAt.filter(new Range()), + ].reverse(); + }, + }, reducers: { - retryFire, submitRetryTask: { params: { name: t.string(), @@ -301,5 +339,5 @@ export function client({ }, }, }, - } as const; + }; } From 0288cdd6495637809ed6baac7bc1d4cdcfacbd75 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 12:08:09 -0400 Subject: [PATCH 16/32] Export SDK types that library declaration files need Libraries that create tables, schemas, and enum builders with this package could not emit .d.ts files because the inferred types named modules outside the package exports (TS2742) or an unexported class with private members (TS4094). The types are exported by name only; runtime exports are unchanged. --- crates/bindings-typescript/src/lib/type_builders.ts | 3 +++ crates/bindings-typescript/src/server/index.ts | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/crates/bindings-typescript/src/lib/type_builders.ts b/crates/bindings-typescript/src/lib/type_builders.ts index 41d2da11015..a2609c24f8e 100644 --- a/crates/bindings-typescript/src/lib/type_builders.ts +++ b/crates/bindings-typescript/src/lib/type_builders.ts @@ -1762,6 +1762,9 @@ class SimpleSumBuilderImpl } } +// Named so declaration files can refer to enum and unit builder instances. +export type { SumBuilderImpl, SimpleSumBuilderImpl, UnitBuilder }; + export const SimpleSumBuilder: { new ( variants: Variants, diff --git a/crates/bindings-typescript/src/server/index.ts b/crates/bindings-typescript/src/server/index.ts index c3a3d3c1458..afcf332ee34 100644 --- a/crates/bindings-typescript/src/server/index.ts +++ b/crates/bindings-typescript/src/server/index.ts @@ -38,4 +38,13 @@ export { ScheduleAt } from '../lib/schedule_at'; export type { Environment } from './environment'; +// Named so libraries built on this package can emit declaration files for +// the tables, schemas, and exports they create. +export type { CoerceRow } from '../lib/table'; +export type { TableSchema } from '../lib/table_schema'; +export type { TablesToSchema } from '../lib/schema'; +export type { EnvironmentValue } from '../lib/environment'; +export type { ReadonlyDbView } from './db_view'; +export type { Schema } from './schema'; + import './polyfills'; // Ensure polyfills are loaded From 7f236216d91b64b60bfd0bcfcddf5d7e534b6f96 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 12:08:19 -0400 Subject: [PATCH 17/32] Ship compiled dist from the core submodule packages cron, crypto, rate-limit, and retry build ESM JavaScript and .d.ts files into dist with tsc (tsconfig.build.json). pnpm pack and publish apply publishConfig, which points main, types, and exports at dist and keeps the subpath names; files lists dist, LICENSE, and README.md. prepack builds before copying the license. Inside the workspace the manifests still point at src, so examples, fixture modules, and tests do not need a build first. Relative imports in src carry .js extensions so the emitted modules resolve in Node as well as in bundlers. rate-limit drops allowImportingTsExtensions like the other packages. --- spacetime-cron-ts/package.json | 19 ++++++++++++++++--- spacetime-cron-ts/src/cron.ts | 8 ++++---- spacetime-cron-ts/src/index.ts | 8 ++++---- spacetime-cron-ts/src/schedule.ts | 6 +++--- spacetime-cron-ts/src/types.ts | 4 ++-- spacetime-cron-ts/tsconfig.build.json | 10 ++++++++++ spacetime-crypto-ts/package.json | 19 ++++++++++++++++--- spacetime-crypto-ts/src/index.ts | 8 ++++---- spacetime-crypto-ts/src/vendors.ts | 4 ++-- spacetime-crypto-ts/tsconfig.build.json | 10 ++++++++++ spacetime-rate-limit-ts/package.json | 19 ++++++++++++++++--- spacetime-rate-limit-ts/scripts/test.ts | 2 +- spacetime-rate-limit-ts/src/index.ts | 2 +- spacetime-rate-limit-ts/src/submodule.ts | 8 ++++---- .../src/submodule/install.ts | 4 ++-- .../src/submodule/operations.ts | 4 ++-- spacetime-rate-limit-ts/tsconfig.build.json | 10 ++++++++++ spacetime-rate-limit-ts/tsconfig.json | 3 +-- spacetime-retry-ts/package.json | 19 ++++++++++++++++--- spacetime-retry-ts/src/index.ts | 4 ++-- spacetime-retry-ts/src/submodule.ts | 2 +- spacetime-retry-ts/tsconfig.build.json | 10 ++++++++++ 22 files changed, 137 insertions(+), 46 deletions(-) create mode 100644 spacetime-cron-ts/tsconfig.build.json create mode 100644 spacetime-crypto-ts/tsconfig.build.json create mode 100644 spacetime-rate-limit-ts/tsconfig.build.json create mode 100644 spacetime-retry-ts/tsconfig.build.json diff --git a/spacetime-cron-ts/package.json b/spacetime-cron-ts/package.json index 4b7175a6dfb..1a0b050d738 100644 --- a/spacetime-cron-ts/package.json +++ b/spacetime-cron-ts/package.json @@ -17,13 +17,25 @@ } }, "files": [ - "src", + "dist", "LICENSE", "README.md" ], "publishConfig": { "access": "public", - "registry": "https://registry.npmjs.org/" + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./parser": { + "types": "./dist/parser.d.ts", + "default": "./dist/parser.js" + } + } }, "repository": { "type": "git", @@ -51,7 +63,8 @@ "test:recovery": "node scripts/test-recovery.mjs", "test:schedule": "tsx scripts/test-schedule.ts", "test:validation": "tsx scripts/test-validation.ts", - "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "dependencies": { diff --git a/spacetime-cron-ts/src/cron.ts b/spacetime-cron-ts/src/cron.ts index 6b264cbcd8f..36a9c8e5e50 100644 --- a/spacetime-cron-ts/src/cron.ts +++ b/spacetime-cron-ts/src/cron.ts @@ -10,7 +10,7 @@ import { type Infer, type VariantsObj, } from 'spacetimedb/server'; -import { errors } from './errors'; +import { errors } from './errors.js'; import { boundedScheduleTime, CronInputError, @@ -24,7 +24,7 @@ import { nextOccurrence, ONE_SECOND_MICROS, truncateError, -} from './schedule'; +} from './schedule.js'; import { cronFireTable, cronJobTable, @@ -38,7 +38,7 @@ import { type CronTx, type FireRow, type JobRow, -} from './tables'; +} from './tables.js'; import type { CronArgsBuilder, CronClient, @@ -52,7 +52,7 @@ import type { CronTableWithArgsOpts, CronTables, ScheduleSpec, -} from './types'; +} from './types.js'; const RECONCILE_REDUCER_NAME = 'cron_reconcile'; const RECONCILE_TICK_KEY = 'cron'; diff --git a/spacetime-cron-ts/src/index.ts b/spacetime-cron-ts/src/index.ts index a919a2fe0e8..afae7976272 100644 --- a/spacetime-cron-ts/src/index.ts +++ b/spacetime-cron-ts/src/index.ts @@ -1,5 +1,5 @@ -export { client, cronTable } from './cron'; -export { errors } from './errors'; +export { client, cronTable } from './cron.js'; +export { errors } from './errors.js'; export type { CronArgsBuilder, CronClient, @@ -19,7 +19,7 @@ export type { CronTx, ScheduleOpts, ScheduleSpec, -} from './types'; +} from './types.js'; export { parseCronExpression, nextFireAfter, @@ -27,4 +27,4 @@ export { MAX_CRON_EXPRESSION_LENGTH, MAX_TIMEZONE_LENGTH, type ParsedCron, -} from './parser'; +} from './parser.js'; diff --git a/spacetime-cron-ts/src/schedule.ts b/spacetime-cron-ts/src/schedule.ts index 9c3a9467538..141fa497a99 100644 --- a/spacetime-cron-ts/src/schedule.ts +++ b/spacetime-cron-ts/src/schedule.ts @@ -4,9 +4,9 @@ import { isValidTimezone, nextFireAfter, parseCronExpression, -} from './parser'; -import { errors } from './errors'; -import type { CronSchedule, ScheduleSpec } from './types'; +} from './parser.js'; +import { errors } from './errors.js'; +import type { CronSchedule, ScheduleSpec } from './types.js'; export const ONE_SECOND_MICROS = 1_000_000n; export const MAX_INTERVAL_SECONDS = 31_536_000; diff --git a/spacetime-cron-ts/src/types.ts b/spacetime-cron-ts/src/types.ts index 0755d35bbee..c1ea018aef2 100644 --- a/spacetime-cron-ts/src/types.ts +++ b/spacetime-cron-ts/src/types.ts @@ -12,9 +12,9 @@ import type { CronRunTableDef, CronTx, FireRow, -} from './tables'; +} from './tables.js'; -export type { CronProcedureCtx, CronTx } from './tables'; +export type { CronProcedureCtx, CronTx } from './tables.js'; export type CronSchedule = | { tag: 'cron'; value: { expression: string; timezone: string } } diff --git a/spacetime-cron-ts/tsconfig.build.json b/spacetime-cron-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-cron-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-crypto-ts/package.json b/spacetime-crypto-ts/package.json index 451b4d59878..1dc6ba7f5f6 100644 --- a/spacetime-crypto-ts/package.json +++ b/spacetime-crypto-ts/package.json @@ -17,13 +17,25 @@ } }, "files": [ - "src", + "dist", "LICENSE", "README.md" ], "publishConfig": { "access": "public", - "registry": "https://registry.npmjs.org/" + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./vendors": { + "types": "./dist/vendors.d.ts", + "default": "./dist/vendors.js" + } + } }, "repository": { "type": "git", @@ -45,7 +57,8 @@ "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", "test": "tsx scripts/test-vectors.ts", - "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "devDependencies": { diff --git a/spacetime-crypto-ts/src/index.ts b/spacetime-crypto-ts/src/index.ts index 3f3c2b9a2e6..af3dead812d 100644 --- a/spacetime-crypto-ts/src/index.ts +++ b/spacetime-crypto-ts/src/index.ts @@ -1,11 +1,11 @@ -export { sha256, SHA256_BYTES } from './sha256'; -export { hmacSha256 } from './hmac'; +export { sha256, SHA256_BYTES } from './sha256.js'; +export { hmacSha256 } from './hmac.js'; export { timingSafeEqual, hexToBytes, bytesToHex, base64ToBytes, -} from './timing'; +} from './timing.js'; export { errors, @@ -17,4 +17,4 @@ export { type GithubVerifyOpts, type VerifyFailure, type VerifyResult, -} from './vendors'; +} from './vendors.js'; diff --git a/spacetime-crypto-ts/src/vendors.ts b/spacetime-crypto-ts/src/vendors.ts index 3fdf867a1cb..a1eb3d3a238 100644 --- a/spacetime-crypto-ts/src/vendors.ts +++ b/spacetime-crypto-ts/src/vendors.ts @@ -3,8 +3,8 @@ // 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'; -import { timingSafeEqual, hexToBytes, base64ToBytes } from './timing'; +import { hmacSha256 } from './hmac.js'; +import { timingSafeEqual, hexToBytes, base64ToBytes } from './timing.js'; const enc = new TextEncoder(); diff --git a/spacetime-crypto-ts/tsconfig.build.json b/spacetime-crypto-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-crypto-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-rate-limit-ts/package.json b/spacetime-rate-limit-ts/package.json index 569f42a013b..c29a4476db4 100644 --- a/spacetime-rate-limit-ts/package.json +++ b/spacetime-rate-limit-ts/package.json @@ -17,13 +17,25 @@ } }, "files": [ - "src", + "dist", "LICENSE", "README.md" ], "publishConfig": { "access": "public", - "registry": "https://registry.npmjs.org/" + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./submodule": { + "types": "./dist/submodule.d.ts", + "default": "./dist/submodule.js" + } + } }, "repository": { "type": "git", @@ -45,7 +57,8 @@ "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", "test": "tsx scripts/test.ts", - "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "peerDependencies": { diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts index ba8a1eca2b9..06ef182f7e8 100644 --- a/spacetime-rate-limit-ts/scripts/test.ts +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -5,7 +5,7 @@ import { MAX_SWEEP_BATCH, sweepRateLimits, type RateLimitBucketRow, -} from '../src/limit.ts'; +} from '../src/limit'; let pass = 0; let fail = 0; diff --git a/spacetime-rate-limit-ts/src/index.ts b/spacetime-rate-limit-ts/src/index.ts index 8e0561d77b6..d78b579d310 100644 --- a/spacetime-rate-limit-ts/src/index.ts +++ b/spacetime-rate-limit-ts/src/index.ts @@ -7,4 +7,4 @@ export { type RateLimitResult, type RateLimitStatus, type RateLimitTxLike, -} from './limit'; +} from './limit.js'; diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts index 777b4381b7b..385d38d74c2 100644 --- a/spacetime-rate-limit-ts/src/submodule.ts +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -1,5 +1,5 @@ -export { default } from './submodule/schema'; -export { install } from './submodule/install'; +export { default } from './submodule/schema.js'; +export { install } from './submodule/install.js'; export { client, errors, @@ -9,7 +9,7 @@ export { type RateLimitResult, type RateLimitStatus, type RateLimitTxLike, -} from './limit'; +} from './limit.js'; export { adminRateLimitBuckets, addRateLimitAdmin, @@ -20,4 +20,4 @@ export { resetBuckets, runSweep, updateConfig, -} from './submodule/operations'; +} from './submodule/operations.js'; diff --git a/spacetime-rate-limit-ts/src/submodule/install.ts b/spacetime-rate-limit-ts/src/submodule/install.ts index 7523b7fc953..b937b4fcf48 100644 --- a/spacetime-rate-limit-ts/src/submodule/install.ts +++ b/spacetime-rate-limit-ts/src/submodule/install.ts @@ -1,6 +1,6 @@ import { ScheduleAt } from 'spacetimedb'; -import { DEFAULT_SWEEP_BATCH } from '../limit'; -import type { ReducerModuleCtx } from './schema'; +import { DEFAULT_SWEEP_BATCH } from '../limit.js'; +import type { ReducerModuleCtx } from './schema.js'; const SWEEP_INTERVAL_MICROS = 30_000_000n; diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts index a74647a7bff..d2160037bd7 100644 --- a/spacetime-rate-limit-ts/src/submodule/operations.ts +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -5,14 +5,14 @@ import { MAX_SWEEP_BATCH, sweepRateLimits, errors, -} from '../limit'; +} from '../limit.js'; import { rateLimitBucket, rateLimitSweepTick, spacetimedb, t, type ViewModuleCtx, -} from './schema'; +} from './schema.js'; /** Whether `identity` is a rate-limit administrator. */ export function isAdmin(db: ViewModuleCtx['db'], identity: Identity): boolean { diff --git a/spacetime-rate-limit-ts/tsconfig.build.json b/spacetime-rate-limit-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-rate-limit-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-rate-limit-ts/tsconfig.json b/spacetime-rate-limit-ts/tsconfig.json index b2b4ecdcdda..77da6c09f65 100644 --- a/spacetime-rate-limit-ts/tsconfig.json +++ b/spacetime-rate-limit-ts/tsconfig.json @@ -7,8 +7,7 @@ "noEmit": true, "skipLibCheck": true, "moduleResolution": "Bundler", - "isolatedModules": true, - "allowImportingTsExtensions": true + "isolatedModules": true }, "include": ["src/**/*.ts", "scripts/**/*.ts"], "exclude": ["node_modules"] diff --git a/spacetime-retry-ts/package.json b/spacetime-retry-ts/package.json index 2a5a9359bd9..eaa4877143d 100644 --- a/spacetime-retry-ts/package.json +++ b/spacetime-retry-ts/package.json @@ -17,13 +17,25 @@ } }, "files": [ - "src", + "dist", "LICENSE", "README.md" ], "publishConfig": { "access": "public", - "registry": "https://registry.npmjs.org/" + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./submodule": { + "types": "./dist/submodule.d.ts", + "default": "./dist/submodule.js" + } + } }, "repository": { "type": "git", @@ -45,7 +57,8 @@ "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", "test": "node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test.ts", - "prepack": "node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" }, "peerDependencies": { diff --git a/spacetime-retry-ts/src/index.ts b/spacetime-retry-ts/src/index.ts index 36e9c07c43c..5826d778abd 100644 --- a/spacetime-retry-ts/src/index.ts +++ b/spacetime-retry-ts/src/index.ts @@ -1,4 +1,4 @@ -export { retryFailed, retryOk, type RetryResult } from './handler'; +export { retryFailed, retryOk, type RetryResult } from './handler.js'; export { client, errors, @@ -12,4 +12,4 @@ export { type RetryTaskRow, type RetryTasks, type RetryViewCtx, -} from './submodule'; +} from './submodule.js'; diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index b3b5db995e7..99c8a211037 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -10,7 +10,7 @@ import { type VariantsObj, } from 'spacetimedb/server'; import type { Identity, Timestamp } from 'spacetimedb'; -import { retryFailed, type RetryResult } from './handler'; +import { retryFailed, type RetryResult } from './handler.js'; const ONE_SECOND_MICROS = 1_000_000n; const MAX_ATTEMPTS = 10; diff --git a/spacetime-retry-ts/tsconfig.build.json b/spacetime-retry-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-retry-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} From 4d594344be918212c11348a66c33f824d9725623 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 16:10:14 -0400 Subject: [PATCH 18/32] Regenerate cron example bindings with CLI 2.11.0 --- spacetime-cron-ts/example/src/module_bindings/app/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spacetime-cron-ts/example/src/module_bindings/app/index.ts b/spacetime-cron-ts/example/src/module_bindings/app/index.ts index 628c885946b..a7dadc03843 100644 --- a/spacetime-cron-ts/example/src/module_bindings/app/index.ts +++ b/spacetime-cron-ts/example/src/module_bindings/app/index.ts @@ -1,7 +1,7 @@ // 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). +// This was generated using spacetimedb cli version 2.11.0 (commit 094df0ed2107fe3a359f5e4ee7a4c344802fc96c). /* eslint-disable */ /* tslint:disable */ @@ -151,7 +151,7 @@ const proceduresSchema = __procedures( /** The remote SpacetimeDB module schema, both runtime and type information. */ const REMOTE_MODULE = { versionInfo: { - cliVersion: "2.10.1" as const, + cliVersion: "2.11.0" as const, }, tables: tablesSchema.schemaType.tables, reducers: reducersSchema.reducersType.reducers, From c57457eed423ee947ad694cd8adf1679bc3713a1 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 16:26:15 -0400 Subject: [PATCH 19/32] Measure cron recovery replays by downtime window Scheduled procedures run in a pool of instances, so later occurrences can execute while the recovery probe blocks and before the host is killed. The fireCount bound counted those runs as replays. Assert on runs scheduled before the restart and completed after the stop, and use a two-second schedule so the pre-kill checks finish before the next occurrence. --- spacetime-cron-ts/scripts/test-recovery.mjs | 38 +++++++++++++-------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/spacetime-cron-ts/scripts/test-recovery.mjs b/spacetime-cron-ts/scripts/test-recovery.mjs index eb5d28295d8..33d8dc43b25 100644 --- a/spacetime-cron-ts/scripts/test-recovery.mjs +++ b/spacetime-cron-ts/scripts/test-recovery.mjs @@ -2,6 +2,9 @@ // 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. +// Procedures run in a pool of instances, so later occurrences can execute while +// the probe blocks. The two-second schedule leaves time for the pre-kill checks +// and the kill before the next occurrence. import * as assert from 'node:assert/strict'; import { spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; @@ -80,12 +83,18 @@ function statusTag(value) { return tag; } +function timestampMillis(value) { + return Number(BigInt(value[0]) / 1000n); +} + function runs() { return sql( - "SELECT invocationId, sequence, status FROM cron_run WHERE jobName = 'recovery_probe'" - ).map(([invocationId, sequence, status]) => ({ + "SELECT invocationId, sequence, scheduledFor, completedAt, status FROM cron_run WHERE jobName = 'recovery_probe'" + ).map(([invocationId, sequence, scheduledFor, completedAt, status]) => ({ invocationId, sequence: BigInt(sequence), + scheduledFor: timestampMillis(scheduledFor), + completedAt: timestampMillis(completedAt), status: statusTag(status), })); } @@ -214,7 +223,7 @@ try { call( 'schedule_cron', JSON.stringify('recovery_probe'), - JSON.stringify('*/1 * * * * *'), + JSON.stringify('*/2 * * * * *'), JSON.stringify('UTC'), '0' ); @@ -254,6 +263,7 @@ try { await stopServer(server); server = undefined; + const stoppedAt = Date.now(); // Leave several calendar occurrences behind us. Recovery should execute at // most one overdue occurrence before resuming from the current time. @@ -261,23 +271,23 @@ try { server = startServer(); await waitForServer(server); + const restartedAt = Date.now(); await poll('a successful post-restart recovery probe', () => { - const observed = runs(); - const recovered = observed.some( - run => run.sequence > 1n && run.status === 'Ok' + const recovered = runs().some( + run => run.completedAt >= restartedAt && run.status === 'Ok' ); const state = job(); - return ( - recovered && - state.enabled && - state.fireCount >= 2n && - state.consecutiveFailures === 0 - ); + return recovered && state.enabled && state.consecutiveFailures === 0; }); await wait(500); + const overdue = runs().filter( + run => run.completedAt >= stoppedAt && run.scheduledFor < restartedAt + ); assert.ok( - job().fireCount <= 3n, - 'calendar recovery must not replay every occurrence missed during downtime' + overdue.length <= 1, + `calendar recovery must not replay every occurrence missed during downtime: ${overdue + .map(run => run.invocationId) + .join(', ')}` ); assert.equal( Number( From dfdccc7e468cc3d378901eac5ee498b4243f4442 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Tue, 29 Sep 2026 16:26:38 -0400 Subject: [PATCH 20/32] Prune retry history before recording an attempt An index scan in a transaction yields rows inserted by that transaction first, so pruning after the insert deleted the new attempt instead of the oldest one once history reached 1,000 rows. --- spacetime-retry-ts/scripts/test.ts | 29 ++++++++++++++++++++--------- spacetime-retry-ts/src/submodule.ts | 12 +++++++----- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts index d04641b4b51..e5252ad505e 100644 --- a/spacetime-retry-ts/scripts/test.ts +++ b/spacetime-retry-ts/scripts/test.ts @@ -39,7 +39,11 @@ const retryFire = retry.retryReducer(schema({ ...retry.tables }), { }); // The mock context implements only the retry tables, not a full reducer // context. -const fire = (arg: Task) => retryFire(ctx as never, { arg }); +const fire = (arg: Task) => { + txInserted.clear(); + retryFire(ctx as never, { arg }); + txInserted.clear(); +}; type History = ReturnType[number]; @@ -53,14 +57,20 @@ let nextTaskId = 0n; let sender = admin; let now = 10_000_000n; -const byRanAt = () => - [...history.values()] - .sort((a, b) => - a.ranAt.microsSinceUnixEpoch === b.ranAt.microsSinceUnixEpoch - ? Number(a.id - b.id) - : Number(a.ranAt.microsSinceUnixEpoch - b.ranAt.microsSinceUnixEpoch) - ) - .values(); +// History rows inserted by the current attempt. Like the datastore, an index +// scan yields them before committed rows. +const txInserted = new Set(); +const byRanAt = () => { + const sorted = [...history.values()].sort((a, b) => + a.ranAt.microsSinceUnixEpoch === b.ranAt.microsSinceUnixEpoch + ? Number(a.id - b.id) + : Number(a.ranAt.microsSinceUnixEpoch - b.ranAt.microsSinceUnixEpoch) + ); + return [ + ...sorted.filter(row => txInserted.has(row.id)), + ...sorted.filter(row => !txInserted.has(row.id)), + ].values(); +}; const ctx: RetryCtx = { get sender() { @@ -87,6 +97,7 @@ const ctx: RetryCtx = { insert(row: History) { const inserted = { ...row, id: ++nextHistoryId }; history.set(inserted.id, inserted); + txInserted.add(inserted.id); return inserted; }, delete: (row: History) => history.delete(row.id), diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index 99c8a211037..251536ade82 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -224,6 +224,13 @@ export function client({ const isLast = !result.ok && arg.attempt + 1 >= arg.maxAttempts; const history = ctx.db.retryHistory; + // Each attempt adds one row, so removing the oldest keeps the bound. Prune + // before inserting: an index scan yields rows inserted in the current + // transaction before committed rows. + if (history.count() >= MAX_ROWS) { + const oldest = history.ranAt.filter(new Range()).next().value; + if (oldest) history.delete(oldest); + } history.insert({ id: 0n, taskName: arg.name, @@ -232,11 +239,6 @@ export function client({ error: result.ok ? undefined : result.error.slice(0, MAX_ERROR_LENGTH), ranAt: ctx.timestamp, }); - // Each attempt adds one row, so removing the oldest keeps the bound. - if (history.count() > MAX_ROWS) { - const oldest = history.ranAt.filter(new Range()).next().value; - if (oldest) history.delete(oldest); - } if (result.ok || isLast) return; const delay = From ca5e6872b51ee0b49ae7595a8ae86e7777c89279 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 12:45:03 -0400 Subject: [PATCH 21/32] Reject rate-limit costs above the limit and export only caller errors --- spacetime-rate-limit-ts/README.md | 17 +++++-- spacetime-rate-limit-ts/package.json | 2 +- .../scripts/sys-abi-test-register.mjs | 27 +++++++++++ spacetime-rate-limit-ts/scripts/test.ts | 38 +++++++++++++-- spacetime-rate-limit-ts/src/limit.ts | 48 ++++++++++++------- .../src/submodule/operations.ts | 2 +- 6 files changed, 106 insertions(+), 28 deletions(-) create mode 100644 spacetime-rate-limit-ts/scripts/sys-abi-test-register.mjs diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index f1ecf866fe4..d1c7044dde4 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -122,20 +122,24 @@ The view returns at most 1,000 rows and returns an empty set to non-admins. `client({ scope, limit, windowSeconds })` configures the policy for one scope. Each scope can be configured once per module; a second `client` call with the -same scope throws `errors.duplicateScope`. When a policy depends on application -state, such as an upgrade tier, create one client per tier with its own scope. +same scope fails module loading with `rate_limit.duplicate_scope`. When a +policy depends on application state, such as an upgrade tier, create one client +per tier with its own scope. The returned limiter exposes `scope`, `limit`, and `windowSeconds`, plus: - `consume(ctx, { key, cost? })` spends `cost` (default 1) from the actor's bucket in the caller's transaction and returns whether it was allowed, the - remaining capacity, the reset time, and the retry delay. + remaining capacity, the reset time, and the retry delay. `cost` must be a + positive integer no greater than `limit`; otherwise `consume` throws + `errors.invalidCost`, since the request could never be allowed. - `peek(db, key, now?)` reads the actor's bucket without spending from it. Views have no clock, so a view reports an expired window until the sweep removes it; compare `resetAt` with the current time, or pass `now` from a reducer or procedure to report an expired window as fresh. `key` identifies the actor; the limiter combines it with the scope. Scopes are -at most 128 characters and keys at most 256. +at most 128 characters. A key must be 1 to 256 characters; otherwise `consume` +and `peek` throw `errors.invalidActorKey`. `install(ctx)` makes the publishing identity the first administrator and schedules a sweep of expired buckets every 30 seconds. Call it from the host's @@ -153,7 +157,10 @@ Admin operations: `resetBuckets({ maxRows })` deletes buckets regardless of expiry. Both remove 500 rows by default and accept at most 10,000 per call. -`errors` exports stable error codes for callers that distinguish failures. +`errors` holds the stable codes a caller can receive as a `SenderError`: +`notAuthorized`, `cannotRemoveLastAdmin`, `invalidActorKey`, `invalidCost`, +`invalidSweepBatch`, and `invalidMaxRows`. An invalid policy passed to `client` +fails module loading instead. Package entrypoints: diff --git a/spacetime-rate-limit-ts/package.json b/spacetime-rate-limit-ts/package.json index c29a4476db4..911bb49ad1e 100644 --- a/spacetime-rate-limit-ts/package.json +++ b/spacetime-rate-limit-ts/package.json @@ -56,7 +56,7 @@ "format": "prettier . --write --ignore-path ../.prettierignore", "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", "typecheck": "tsc --noEmit", - "test": "tsx scripts/test.ts", + "test": "node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test.ts", "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" diff --git a/spacetime-rate-limit-ts/scripts/sys-abi-test-register.mjs b/spacetime-rate-limit-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..30107456e71 --- /dev/null +++ b/spacetime-rate-limit-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,27 @@ +import { register } from 'node:module'; + +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; + +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; + export function resolve(specifier, context, nextResolve) { + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts index 06ef182f7e8..4f8df94b90f 100644 --- a/spacetime-rate-limit-ts/scripts/test.ts +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -1,4 +1,5 @@ import { Timestamp } from 'spacetimedb'; +import { SenderError } from 'spacetimedb/server'; import { client, errors, @@ -22,12 +23,17 @@ function assert(cond: boolean, name: string, detail = ''): void { } } -function assertThrows(fn: () => void, expected: string, name: string): void { +function assertThrows( + fn: () => void, + expected: string, + name: string, + type: new (message: string) => Error = Error +): void { try { fn(); assert(false, name, `expected ${expected}`); } catch (error) { - assert(error instanceof Error && error.message === expected, name); + assert(error instanceof type && error.message === expected, name); } } @@ -74,13 +80,37 @@ process.stdout.write('\nrate limiter\n'); ); assertThrows( () => client({ scope: 'tap', windowSeconds: 30, limit: 5 }), - errors.duplicateScope, + 'rate_limit.duplicate_scope', 'a scope can be configured once' ); assertThrows( () => tap.consume(tx, { key: '' }), errors.invalidActorKey, - 'empty actor key rejected' + 'empty actor key rejected', + SenderError + ); +} + +{ + const tx = makeTx(); + const upload = client({ scope: 'upload', limit: 3, windowSeconds: 60 }); + assertThrows( + () => upload.consume(tx, { key: 'alice', cost: 4 }), + errors.invalidCost, + 'cost above the limit rejected', + SenderError + ); + assertThrows( + () => upload.consume(tx, { key: 'alice', cost: 0 }), + errors.invalidCost, + 'non-positive cost rejected', + SenderError + ); + assert(tx.rows.size === 0, 'rejected cost leaves the bucket untouched'); + const full = upload.consume(tx, { key: 'alice', cost: 3 }); + assert( + full.allowed && full.remaining === 0, + 'cost equal to the limit allowed' ); } diff --git a/spacetime-rate-limit-ts/src/limit.ts b/spacetime-rate-limit-ts/src/limit.ts index 0fd0710d9a5..e658ee446e6 100644 --- a/spacetime-rate-limit-ts/src/limit.ts +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -1,4 +1,5 @@ import { Timestamp } from 'spacetimedb'; +import { SenderError } from 'spacetimedb/server'; const ONE_SECOND_MICROS = 1_000_000n; const U32_MAX = 0xffff_ffff; @@ -8,18 +9,22 @@ export const MAX_SWEEP_BATCH = 10_000; const MAX_SCOPE_LENGTH = 128; const MAX_ACTOR_KEY_LENGTH = 256; +/** Codes a reducer, procedure, or view caller can receive as a `SenderError`. */ export const errors = { notAuthorized: 'rate_limit.not_authorized', cannotRemoveLastAdmin: 'rate_limit.cannot_remove_last_admin', - invalidScope: 'rate_limit.invalid_scope', - duplicateScope: 'rate_limit.duplicate_scope', invalidActorKey: 'rate_limit.invalid_actor_key', - invalidLimit: 'rate_limit.invalid_limit', - invalidWindow: 'rate_limit.invalid_window', invalidCost: 'rate_limit.invalid_cost', invalidSweepBatch: 'rate_limit.invalid_sweep_batch', invalidMaxRows: 'rate_limit.invalid_max_rows', - configMissing: 'rate_limit.config_missing', +} as const; + +// Policy errors fail the host module while it loads, before any caller. +const policyErrors = { + invalidScope: 'rate_limit.invalid_scope', + duplicateScope: 'rate_limit.duplicate_scope', + invalidLimit: 'rate_limit.invalid_limit', + invalidWindow: 'rate_limit.invalid_window', } as const; export interface RateLimitPolicy { @@ -90,10 +95,8 @@ export interface RateLimitTxLike { }; } -function assertPositiveInt(code: string, value: number, max = U32_MAX): void { - if (!Number.isInteger(value) || value <= 0 || value > max) { - throw new Error(code); - } +function isPositiveInt(value: number, max = U32_MAX): boolean { + return Number.isInteger(value) && value > 0 && value <= max; } function secondsUntil(now: Timestamp, future: Timestamp): number { @@ -102,6 +105,8 @@ function secondsUntil(now: Timestamp, future: Timestamp): number { return Number((delta + ONE_SECOND_MICROS - 1n) / ONE_SECOND_MICROS); } +// Module state lasts for one evaluation of the host module. SpacetimeDB +// evaluates it once in each fresh worker isolate. const registeredScopes = new Set(); /** @@ -110,15 +115,16 @@ const registeredScopes = new Set(); */ export function client({ scope, limit, windowSeconds }: RateLimitPolicy) { if (scope.length === 0 || scope.length > MAX_SCOPE_LENGTH) - throw new Error(errors.invalidScope); - assertPositiveInt(errors.invalidLimit, limit); - assertPositiveInt(errors.invalidWindow, windowSeconds); - if (registeredScopes.has(scope)) throw new Error(errors.duplicateScope); + throw new Error(policyErrors.invalidScope); + if (!isPositiveInt(limit)) throw new Error(policyErrors.invalidLimit); + if (!isPositiveInt(windowSeconds)) + throw new Error(policyErrors.invalidWindow); + if (registeredScopes.has(scope)) throw new Error(policyErrors.duplicateScope); registeredScopes.add(scope); function bucketKey(actorKey: string): string { if (actorKey.length === 0 || actorKey.length > MAX_ACTOR_KEY_LENGTH) - throw new Error(errors.invalidActorKey); + throw new SenderError(errors.invalidActorKey); // Length-prefix both parts so delimiters inside them cannot collide. return `${scope.length}:${scope}${actorKey.length}:${actorKey}`; } @@ -128,14 +134,20 @@ export function client({ scope, limit, windowSeconds }: RateLimitPolicy) { limit, windowSeconds, - /** Spend `cost` (default 1) from the actor's bucket in the caller's transaction. */ + /** + * Spend `cost` (default 1) from the actor's bucket in the caller's + * transaction. A cost above `limit` can never be allowed, so it throws + * `errors.invalidCost`. + */ consume( tx: RateLimitTxLike, opts: { key: string; cost?: number } ): RateLimitResult { const key = bucketKey(opts.key); const cost = opts.cost ?? 1; - assertPositiveInt(errors.invalidCost, cost); + if (!isPositiveInt(cost, limit)) { + throw new SenderError(errors.invalidCost); + } const now = tx.timestamp; const existing = tx.db.rateLimitBucket.key.find(key); const open = @@ -221,7 +233,9 @@ export function sweepRateLimits( expiredRows: Iterable, maxRows: number ): number { - assertPositiveInt(errors.invalidSweepBatch, maxRows, MAX_SWEEP_BATCH); + if (!isPositiveInt(maxRows, MAX_SWEEP_BATCH)) { + throw new Error(errors.invalidSweepBatch); + } const now = tx.timestamp.microsSinceUnixEpoch; let deleted = 0; for (const row of expiredRows) { diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts index d2160037bd7..86032bc3042 100644 --- a/spacetime-rate-limit-ts/src/submodule/operations.ts +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -88,7 +88,7 @@ export const updateConfig = spacetimedb.reducer( (ctx, args) => { requireAdmin(ctx); const cfg = ctx.db.rateLimitConfig.singleton.find(true); - if (!cfg) throw new Error(errors.configMissing); + if (!cfg) throw new Error('rate_limit.config_missing'); ctx.db.rateLimitConfig.singleton.update({ ...cfg, sweepBatch: positiveU32( From 313ce60c64b57c1121a3cfa9ca250c04b52a3faf Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 12:45:54 -0400 Subject: [PATCH 22/32] Give up retry tasks whose handler throws a SenderError --- spacetime-retry-ts/README.md | 4 +++- spacetime-retry-ts/scripts/test.ts | 16 +++++++++++++--- spacetime-retry-ts/src/submodule.ts | 6 +++++- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md index ae1ccc7bc25..1a7cbd59e38 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -64,7 +64,9 @@ 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 +failed attempt and schedules the next attempt, up to `maxAttempts`. A thrown +`SenderError` marks the task's arguments as invalid: Retry records the attempt +as `GaveUp` with the error message and schedules nothing further. 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. diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts index e5252ad505e..21e0138e733 100644 --- a/spacetime-retry-ts/scripts/test.ts +++ b/spacetime-retry-ts/scripts/test.ts @@ -1,6 +1,6 @@ import * as assert from 'node:assert/strict'; import { Identity, Timestamp } from 'spacetimedb'; -import { ScheduleAt, schema, t } from 'spacetimedb/server'; +import { ScheduleAt, schema, SenderError, t } from 'spacetimedb/server'; import { client, errors, @@ -16,6 +16,7 @@ const sharedArgs = t.object('TestArgs', { value: t.string() }); const retry = client({ tasks: { throws: t.unit(), + rejects: t.unit(), fails: t.unit(), succeeds: t.unit(), first: sharedArgs, @@ -26,6 +27,9 @@ const retryFire = retry.retryReducer(schema({ ...retry.tables }), { throws() { throw new Error('x'.repeat(3000)); }, + rejects() { + throw new SenderError('order.not_found'); + }, fails: () => retryFailed('unavailable'), succeeds: () => retryOk(), first(_ctx, args) { @@ -199,6 +203,12 @@ fire({ ...task, args: { tag: 'toString' } }); assert.equal(history.get(5n)?.error, `${errors.unknownHandler}:toString`); assert.equal(tasks.size, 4); +// A SenderError gives up on the first attempt without scheduling another. +fire({ ...task, args: { tag: 'rejects' } }); +assert.equal(history.get(6n)?.status.tag, 'GaveUp'); +assert.equal(history.get(6n)?.error, 'order.not_found'); +assert.equal(tasks.size, 4); + // The newest pending tasks come first. assert.deepEqual( retry.views.retryTasksAdmin(ctx).map(row => row.scheduledId), @@ -212,8 +222,8 @@ for (let i = 0; i < 1000; i++) { } assert.equal(tasks.size, 4); assert.equal(history.size, 1000); -assert.equal(history.has(5n), false); -assert.equal(history.has(6n), true); +assert.equal(history.has(6n), false); +assert.equal(history.has(7n), true); const recent = retry.views.retryHistoryAdmin(ctx); assert.equal(recent.length, 1000); assert.equal(recent[0].id, nextHistoryId); diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index 251536ade82..23dd7f2e1ee 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -209,6 +209,7 @@ export function client({ arg: RetryTaskRow ): void { let result: RetryResult; + let permanent = false; try { const { tag } = arg.args; if (!Object.prototype.hasOwnProperty.call(handlers, tag)) { @@ -217,12 +218,15 @@ export function client({ result = handlers[tag](ctx, 'value' in arg.args ? arg.args.value : {}); } catch (error) { // A caught exception does not roll back the handler's earlier writes. + // A `SenderError` rejects the task's arguments, so retrying cannot help. + permanent = error instanceof SenderError; result = retryFailed( error instanceof Error ? error.message : String(error) ); } - const isLast = !result.ok && arg.attempt + 1 >= arg.maxAttempts; + const isLast = + !result.ok && (permanent || arg.attempt + 1 >= arg.maxAttempts); const history = ctx.db.retryHistory; // Each attempt adds one row, so removing the oldest keeps the bound. Prune // before inserting: an index scan yields rows inserted in the current From 45fe0a3e3266798af75fda69ba4180d48896304f Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 12:46:52 -0400 Subject: [PATCH 23/32] Lint submodules and run the cron recovery test in CI --- .github/workflows/ci.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a999a21b381..139f53e31a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1702,15 +1702,19 @@ jobs: - *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" + - *expose-spacetime-cli - name: Check submodules run: | + pnpm -r -F "./spacetime-*-ts/**" run lint pnpm -r -F "./spacetime-*-ts/**" run typecheck pnpm -r -F "./spacetime-*-ts/**" run test + # Starts an isolated server on a free local port with a temporary data + # directory. `spacetime start` runs the extracted spacetimedb-standalone + # beside spacetimedb-cli. + - name: Run cron crash-recovery test + run: pnpm --dir spacetime-cron-ts run test:recovery + - name: Build submodule packages and examples run: pnpm -r -F "./spacetime-*-ts/**" run build From d4447c6a5235b3e9aaa566ce6b90ba5196a79c8b Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 12:49:12 -0400 Subject: [PATCH 24/32] Rename submodule-shared to example-ui --- eslint.config.js | 2 +- pnpm-lock.yaml | 50 +++++++++---------- spacetime-cron-ts/example/package.json | 2 +- spacetime-cron-ts/example/server.ts | 2 +- .../.npmrc | 0 .../assets/brand.svg | 0 .../assets/logo.svg | 0 .../package.json | 2 +- .../scripts/auth.test.ts | 0 .../scripts/server.test.ts | 2 +- .../src/auth-panel.ts | 0 .../src/icons.ts | 0 .../src/index.ts | 0 .../src/server.ts | 0 .../src/styles/index.css | 0 .../tsconfig.json | 0 spacetime-rate-limit-ts/example/package.json | 2 +- spacetime-rate-limit-ts/example/server.ts | 2 +- 18 files changed, 32 insertions(+), 32 deletions(-) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/.npmrc (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/assets/brand.svg (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/assets/logo.svg (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/package.json (95%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/scripts/auth.test.ts (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/scripts/server.test.ts (95%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/src/auth-panel.ts (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/src/icons.ts (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/src/index.ts (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/src/server.ts (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/src/styles/index.css (100%) rename {spacetime-submodule-shared-ts => spacetime-example-ui-ts}/tsconfig.json (100%) diff --git a/eslint.config.js b/eslint.config.js index 302384c32a2..ad7583f71c7 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -65,7 +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', + './spacetime-example-ui-ts/tsconfig.json', './templates/react-ts/tsconfig.json', './templates/chat-react-ts/tsconfig.json', './templates/money-exchange-react-ts/tsconfig.json', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 49ca2adc154..eac067244b5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -367,9 +367,9 @@ importers: spacetime-cron-ts/example: dependencies: - '@spacetimedb/submodule-shared': + '@spacetimedb/example-ui': specifier: workspace:* - version: link:../../spacetime-submodule-shared-ts + version: link:../../spacetime-example-ui-ts dotenv: specifier: ^16.4.7 version: 16.6.1 @@ -450,6 +450,27 @@ importers: specifier: ^5.9.3 version: 5.9.3 + spacetime-example-ui-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.21.0)(yaml@2.8.2) + spacetime-rate-limit-ts: devDependencies: '@types/node': @@ -473,9 +494,9 @@ importers: spacetime-rate-limit-ts/example: dependencies: - '@spacetimedb/submodule-shared': + '@spacetimedb/example-ui': specifier: workspace:* - version: link:../../spacetime-submodule-shared-ts + version: link:../../spacetime-example-ui-ts dotenv: specifier: ^16.4.7 version: 16.6.1 @@ -571,27 +592,6 @@ importers: 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.21.0)(yaml@2.8.2) - templates/angular-ts: dependencies: '@angular/common': diff --git a/spacetime-cron-ts/example/package.json b/spacetime-cron-ts/example/package.json index 46b087eebd9..ae3e62fda24 100644 --- a/spacetime-cron-ts/example/package.json +++ b/spacetime-cron-ts/example/package.json @@ -13,7 +13,7 @@ "dev": "pnpm run build && tsx server.ts" }, "dependencies": { - "@spacetimedb/submodule-shared": "workspace:*", + "@spacetimedb/example-ui": "workspace:*", "dotenv": "^16.4.7", "express": "^4.21.2", "spacetimedb": "workspace:*" diff --git a/spacetime-cron-ts/example/server.ts b/spacetime-cron-ts/example/server.ts index ee49651af4a..fced927aae4 100644 --- a/spacetime-cron-ts/example/server.ts +++ b/spacetime-cron-ts/example/server.ts @@ -3,7 +3,7 @@ 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'; +import { exampleUiAssetsDir } from '@spacetimedb/example-ui/server'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); diff --git a/spacetime-submodule-shared-ts/.npmrc b/spacetime-example-ui-ts/.npmrc similarity index 100% rename from spacetime-submodule-shared-ts/.npmrc rename to spacetime-example-ui-ts/.npmrc diff --git a/spacetime-submodule-shared-ts/assets/brand.svg b/spacetime-example-ui-ts/assets/brand.svg similarity index 100% rename from spacetime-submodule-shared-ts/assets/brand.svg rename to spacetime-example-ui-ts/assets/brand.svg diff --git a/spacetime-submodule-shared-ts/assets/logo.svg b/spacetime-example-ui-ts/assets/logo.svg similarity index 100% rename from spacetime-submodule-shared-ts/assets/logo.svg rename to spacetime-example-ui-ts/assets/logo.svg diff --git a/spacetime-submodule-shared-ts/package.json b/spacetime-example-ui-ts/package.json similarity index 95% rename from spacetime-submodule-shared-ts/package.json rename to spacetime-example-ui-ts/package.json index 83ee4fa12af..a14a64a8de3 100644 --- a/spacetime-submodule-shared-ts/package.json +++ b/spacetime-example-ui-ts/package.json @@ -1,5 +1,5 @@ { - "name": "@spacetimedb/submodule-shared", + "name": "@spacetimedb/example-ui", "description": "Shared UI and server utilities for SpacetimeDB submodule examples.", "version": "0.1.0", "private": true, diff --git a/spacetime-submodule-shared-ts/scripts/auth.test.ts b/spacetime-example-ui-ts/scripts/auth.test.ts similarity index 100% rename from spacetime-submodule-shared-ts/scripts/auth.test.ts rename to spacetime-example-ui-ts/scripts/auth.test.ts diff --git a/spacetime-submodule-shared-ts/scripts/server.test.ts b/spacetime-example-ui-ts/scripts/server.test.ts similarity index 95% rename from spacetime-submodule-shared-ts/scripts/server.test.ts rename to spacetime-example-ui-ts/scripts/server.test.ts index 3162aa88da1..de9df7ebcd8 100644 --- a/spacetime-submodule-shared-ts/scripts/server.test.ts +++ b/spacetime-example-ui-ts/scripts/server.test.ts @@ -12,7 +12,7 @@ import { const temporaryDirectories: string[] = []; function temporaryTokenPath(): string { - const directory = mkdtempSync(path.join(tmpdir(), 'stdb-submodule-shared-')); + const directory = mkdtempSync(path.join(tmpdir(), 'stdb-example-ui-')); temporaryDirectories.push(directory); return path.join(directory, 'server-token'); } diff --git a/spacetime-submodule-shared-ts/src/auth-panel.ts b/spacetime-example-ui-ts/src/auth-panel.ts similarity index 100% rename from spacetime-submodule-shared-ts/src/auth-panel.ts rename to spacetime-example-ui-ts/src/auth-panel.ts diff --git a/spacetime-submodule-shared-ts/src/icons.ts b/spacetime-example-ui-ts/src/icons.ts similarity index 100% rename from spacetime-submodule-shared-ts/src/icons.ts rename to spacetime-example-ui-ts/src/icons.ts diff --git a/spacetime-submodule-shared-ts/src/index.ts b/spacetime-example-ui-ts/src/index.ts similarity index 100% rename from spacetime-submodule-shared-ts/src/index.ts rename to spacetime-example-ui-ts/src/index.ts diff --git a/spacetime-submodule-shared-ts/src/server.ts b/spacetime-example-ui-ts/src/server.ts similarity index 100% rename from spacetime-submodule-shared-ts/src/server.ts rename to spacetime-example-ui-ts/src/server.ts diff --git a/spacetime-submodule-shared-ts/src/styles/index.css b/spacetime-example-ui-ts/src/styles/index.css similarity index 100% rename from spacetime-submodule-shared-ts/src/styles/index.css rename to spacetime-example-ui-ts/src/styles/index.css diff --git a/spacetime-submodule-shared-ts/tsconfig.json b/spacetime-example-ui-ts/tsconfig.json similarity index 100% rename from spacetime-submodule-shared-ts/tsconfig.json rename to spacetime-example-ui-ts/tsconfig.json diff --git a/spacetime-rate-limit-ts/example/package.json b/spacetime-rate-limit-ts/example/package.json index d9fd9da62b8..040123411dd 100644 --- a/spacetime-rate-limit-ts/example/package.json +++ b/spacetime-rate-limit-ts/example/package.json @@ -14,7 +14,7 @@ "dev": "pnpm run build && tsx server.ts" }, "dependencies": { - "@spacetimedb/submodule-shared": "workspace:*", + "@spacetimedb/example-ui": "workspace:*", "dotenv": "^16.4.7", "express": "^4.21.2", "spacetimedb": "workspace:*" diff --git a/spacetime-rate-limit-ts/example/server.ts b/spacetime-rate-limit-ts/example/server.ts index 5429fba7566..a869599910a 100644 --- a/spacetime-rate-limit-ts/example/server.ts +++ b/spacetime-rate-limit-ts/example/server.ts @@ -2,7 +2,7 @@ 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'; +import { exampleUiAssetsDir } from '@spacetimedb/example-ui/server'; dotenv.config(); From 8f680667c1a763f8c90b98a351cf28add9a6dbbc Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 12:53:12 -0400 Subject: [PATCH 25/32] Export only runtime cron error codes --- spacetime-cron-ts/README.md | 17 +++++++- .../scripts/test-registration.ts | 14 +++---- spacetime-cron-ts/src/cron.ts | 42 ++++++++++--------- spacetime-cron-ts/src/errors.ts | 38 +++++++++++------ spacetime-cron-ts/src/schedule.ts | 8 ++-- 5 files changed, 73 insertions(+), 46 deletions(-) diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md index 235d7969bcf..fe39857a1c3 100644 --- a/spacetime-cron-ts/README.md +++ b/spacetime-cron-ts/README.md @@ -217,11 +217,24 @@ cron.unschedule(ctx, cleanup); These helpers perform scheduling operations. Application reducers remain responsible for authorization. -Input errors from `cron.schedule()` are thrown as `SenderError`s. Every code -thrown by the package is exported as `errors`, for example +Input errors from `cron.schedule()` are thrown as `SenderError`s. `errors` +holds the codes a caller can receive at runtime, for example `errors.invalidExpression` (`cron.invalid_expression`). Codes may be followed by `:` and detail text. +- `notAuthorized`: a client called a `_cron` function directly. +- `invalidMaxFailures`, `invalidInterval`, `invalidExpression`, + `invalidTimezone`, `unsatisfiableExpression`, `missingArgs`, and + `unexpectedArgs`: `cron.schedule()` rejected its input. +- `invalidScheduleState`, `invalidArgsState`, `invalidTrigger`, and + `noFutureOccurrence`: stored in the private `cron_job.disabledReason` when + cron disables a job. + +Programming errors, such as invalid job definitions or client configuration, +missing handler registration, a job handle from another client, or a handler +that returns a promise, fail module loading or the call with `cron.*` codes +that are not exported. + ### Database state The package adds these shared tables: diff --git a/spacetime-cron-ts/scripts/test-registration.ts b/spacetime-cron-ts/scripts/test-registration.ts index 1c3162b7863..1f554755447 100644 --- a/spacetime-cron-ts/scripts/test-registration.ts +++ b/spacetime-cron-ts/scripts/test-registration.ts @@ -1,7 +1,7 @@ import * as assert from 'node:assert/strict'; import { schema } from 'spacetimedb/server'; import { client, cronTable, publicDisabledReason } from '../src/cron'; -import { errors } from '../src/errors'; +import { errors, internalErrors } from '../src/errors'; const expectCode = (code: string) => ({ message: new RegExp(`^${code}(:|$)`), @@ -14,15 +14,15 @@ const expectCode = (code: string) => ({ client({ jobs: [other] }); assert.throws( () => cron.unschedule({} as never, other), - expectCode(errors.foreignJobHandle) + expectCode(internalErrors.foreignJobHandle) ); assert.throws( () => client({ jobs: [{ jobName: 'plain' }] }), - expectCode(errors.foreignJobHandle) + expectCode(internalErrors.foreignJobHandle) ); } -assert.throws(() => client({ jobs: [] }), expectCode(errors.noJobs)); +assert.throws(() => client({ jobs: [] }), expectCode(internalErrors.noJobs)); { const job = cronTable({ name: 'duplicate' }); @@ -82,7 +82,7 @@ assert.throws(() => client({ jobs: [] }), expectCode(errors.noJobs)); job.cronReducer(spacetimedb, () => {}); assert.throws( () => cron.reconcileReducer(spacetimedb), - expectCode(errors.reconcileNotConfigured) + expectCode(internalErrors.reconcileNotConfigured) ); } @@ -94,7 +94,7 @@ assert.throws(() => client({ jobs: [] }), expectCode(errors.noJobs)); cron.reconcileReducer(spacetimedb); assert.throws( () => cron.reconcileReducer(spacetimedb), - expectCode(errors.reconcileReducerAlreadyRegistered) + expectCode(internalErrors.reconcileReducerAlreadyRegistered) ); } @@ -105,7 +105,7 @@ assert.throws(() => client({ jobs: [] }), expectCode(errors.noJobs)); cron.publicViews(spacetimedb); assert.throws( () => cron.publicViews(spacetimedb), - expectCode(errors.publicViewsAlreadyRegistered) + expectCode(internalErrors.publicViewsAlreadyRegistered) ); } diff --git a/spacetime-cron-ts/src/cron.ts b/spacetime-cron-ts/src/cron.ts index 36a9c8e5e50..2865277631b 100644 --- a/spacetime-cron-ts/src/cron.ts +++ b/spacetime-cron-ts/src/cron.ts @@ -10,7 +10,7 @@ import { type Infer, type VariantsObj, } from 'spacetimedb/server'; -import { errors } from './errors.js'; +import { errors, internalErrors } from './errors.js'; import { boundedScheduleTime, CronInputError, @@ -141,7 +141,7 @@ function invocationId( function requireMetadata(job: CronJobReference): JobMetadata { const value = metadata.get(job); - if (!value) throw new Error(errors.foreignJobHandle); + if (!value) throw new Error(internalErrors.foreignJobHandle); return value; } @@ -149,7 +149,7 @@ function requireCore(job: CronJobReference): Core { const value = requireMetadata(job).core; if (!value) { throw new Error( - `${errors.notWired}:${job.jobName}:pass the job to client() first` + `${internalErrors.notWired}:${job.jobName}:pass the job to client() first` ); } return value; @@ -160,14 +160,14 @@ function requireRegisteredHandlers(core: Core): void { .filter(job => !job.registration) .map(job => job.handle.jobName); if (missing.length > 0) { - throw new Error(`${errors.missingHandlers}:${missing.join(',')}`); + throw new Error(`${internalErrors.missingHandlers}:${missing.join(',')}`); } } function requireFire(job: JobMetadata): CronFireTableDef { if (!job.fire) { throw new Error( - `${errors.notWired}:${job.handle.jobName}:pass the job to client() first` + `${internalErrors.notWired}:${job.handle.jobName}:pass the job to client() first` ); } return job.fire; @@ -185,7 +185,7 @@ function fireTable(ctx: CronTx, job: JobMetadata): CronFireTable { const value = ctx.db[job.fireAccessor]; if (!value) { throw new Error( - `${errors.missingTable}:${job.fireTableName}:spread cron.tables into schema()` + `${internalErrors.missingTable}:${job.fireTableName}:spread cron.tables into schema()` ); } // The accessor was derived from the fire table registered by client(). @@ -311,13 +311,13 @@ function ensureReconcileTick(ctx: CronTx, core: Core): void { if (everySeconds === undefined) return; if (!core.reconcileRegistered) { throw new Error( - `${errors.reconcileReducerNotRegistered}:export cron.reconcileReducer()` + `${internalErrors.reconcileReducerNotRegistered}:export cron.reconcileReducer()` ); } const tick = ctx.db.cronReconcileTick; if (!tick) { throw new Error( - `${errors.missingTable}:cron_reconcile_tick:spread cron.tables into schema()` + `${internalErrors.missingTable}:cron_reconcile_tick:spread cron.tables into schema()` ); } if (tick.key.find(RECONCILE_TICK_KEY)) return; @@ -551,7 +551,7 @@ function executeReducer( const result = invokeHandler(handler, ctx, job, prepared); if (isThenable(result)) { throw new Error( - `${errors.asyncReducerHandler}:reducers must complete synchronously` + `${internalErrors.asyncReducerHandler}:reducers must complete synchronously` ); } } catch (error) { @@ -577,7 +577,7 @@ function executeProcedure( ): void { requireDatabaseCaller(ctx); if (arg.recovery) { - throw new SenderError(errors.invalidProcedureRecovery); + throw new SenderError(internalErrors.invalidProcedureRecovery); } const prepared = ctx.withTx(tx => prepareFire(tx, job, arg, true)); if (!prepared) return; @@ -587,7 +587,7 @@ function executeProcedure( const result = invokeHandler(handler, ctx, job, prepared); if (isThenable(result)) { throw new Error( - `${errors.asyncProcedureHandler}:procedures must complete synchronously` + `${internalErrors.asyncProcedureHandler}:procedures must complete synchronously` ); } } catch (caught) { @@ -661,7 +661,7 @@ function registerJob(job: JobMetadata, kind: 'reducer' | 'procedure'): Core { const core = requireCore(job.handle); if (job.registration) { throw new Error( - `${errors.handlerAlreadyRegistered}:${job.handle.jobName}:${job.registration}` + `${internalErrors.handlerAlreadyRegistered}:${job.handle.jobName}:${job.registration}` ); } job.registration = kind; @@ -731,7 +731,7 @@ export function client( config: Config ): CronClient { const { jobs } = config; - if (jobs.length === 0) throw new Error(errors.noJobs); + if (jobs.length === 0) throw new Error(internalErrors.noJobs); const historyCap = normalizeHistoryCap(config.historyCap); const isPublic = config.publicTables ?? false; const reconcileEverySeconds = normalizeReconcileEverySeconds( @@ -747,13 +747,15 @@ export function client( for (const handle of sortedJobs) { const job = requireMetadata(handle); if (jobsByName.has(handle.jobName)) { - throw new Error(`${errors.duplicateJob}:${handle.jobName}`); + throw new Error(`${internalErrors.duplicateJob}:${handle.jobName}`); } if (job.core) { - throw new Error(`${errors.jobAlreadyWired}:${handle.jobName}`); + throw new Error(`${internalErrors.jobAlreadyWired}:${handle.jobName}`); } if (usedAccessors.has(job.fireAccessor)) { - throw new Error(`${errors.tableKeyCollision}:${job.fireAccessor}`); + throw new Error( + `${internalErrors.tableKeyCollision}:${job.fireAccessor}` + ); } usedAccessors.add(job.fireAccessor); jobsByName.set(handle.jobName, job); @@ -786,18 +788,18 @@ export function client( function jobInThisClient(handle: CronJobReference): JobMetadata { const job = requireMetadata(handle); - if (job.core !== core) throw new Error(errors.foreignJobHandle); + if (job.core !== core) throw new Error(internalErrors.foreignJobHandle); return job; } function reconcileReducer(spacetimedb: CronSchema) { if (core.reconcileRegistered) { - throw new Error(errors.reconcileReducerAlreadyRegistered); + throw new Error(internalErrors.reconcileReducerAlreadyRegistered); } const tick = core.reconcileTick; if (tick === undefined) { throw new Error( - `${errors.reconcileNotConfigured}:set client({ reconcileEverySeconds })` + `${internalErrors.reconcileNotConfigured}:set client({ reconcileEverySeconds })` ); } requireRegisteredHandlers(core); @@ -814,7 +816,7 @@ export function client( function publicViews(spacetimedb: CronSchema): CronPublicViews { if (core.publicViewsRegistered) { - throw new Error(errors.publicViewsAlreadyRegistered); + throw new Error(internalErrors.publicViewsAlreadyRegistered); } core.publicViewsRegistered = true; const jobsView = spacetimedb.anonymousView( diff --git a/spacetime-cron-ts/src/errors.ts b/spacetime-cron-ts/src/errors.ts index 91a43cfcb00..dec3625de48 100644 --- a/spacetime-cron-ts/src/errors.ts +++ b/spacetime-cron-ts/src/errors.ts @@ -1,6 +1,30 @@ -/** Codes thrown by cron. Some are followed by `:` and detail text. */ +/** + * Codes a caller can receive at runtime. `schedule()` throws the input codes as + * `SenderError`s; the disabled-reason codes are stored on the job row. Some are + * followed by `:` and detail text. + */ export const errors = { notAuthorized: 'cron.not_authorized', + // Thrown by `schedule()`. + invalidMaxFailures: 'cron.invalid_max_failures', + invalidInterval: 'cron.invalid_interval', + invalidExpression: 'cron.invalid_expression', + invalidTimezone: 'cron.invalid_timezone', + unsatisfiableExpression: 'cron.unsatisfiable_expression', + missingArgs: 'cron.missing_args', + unexpectedArgs: 'cron.unexpected_args', + // Stored as a job's disabled reason. + invalidScheduleState: 'cron.invalid_schedule_state', + invalidArgsState: 'cron.invalid_args_state', + invalidTrigger: 'cron.invalid_trigger', + noFutureOccurrence: 'cron.no_future_occurrence', +} as const; + +/** + * Module-definition and handler programming errors. They fail module loading + * or an invocation and are not exported from the package. + */ +export const internalErrors = { foreignJobHandle: 'cron.foreign_job_handle', notWired: 'cron.not_wired', noJobs: 'cron.no_jobs', @@ -21,16 +45,4 @@ export const errors = { invalidJobName: 'cron.invalid_job_name', invalidHistoryCap: 'cron.invalid_history_cap', invalidReconcileInterval: 'cron.invalid_reconcile_interval', - invalidMaxFailures: 'cron.invalid_max_failures', - invalidInterval: 'cron.invalid_interval', - invalidExpression: 'cron.invalid_expression', - invalidTimezone: 'cron.invalid_timezone', - unsatisfiableExpression: 'cron.unsatisfiable_expression', - missingArgs: 'cron.missing_args', - unexpectedArgs: 'cron.unexpected_args', - // Stored as a job's disabled reason. - invalidScheduleState: 'cron.invalid_schedule_state', - invalidArgsState: 'cron.invalid_args_state', - invalidTrigger: 'cron.invalid_trigger', - noFutureOccurrence: 'cron.no_future_occurrence', } as const; diff --git a/spacetime-cron-ts/src/schedule.ts b/spacetime-cron-ts/src/schedule.ts index 141fa497a99..a8637e24fe5 100644 --- a/spacetime-cron-ts/src/schedule.ts +++ b/spacetime-cron-ts/src/schedule.ts @@ -5,7 +5,7 @@ import { nextFireAfter, parseCronExpression, } from './parser.js'; -import { errors } from './errors.js'; +import { errors, internalErrors } from './errors.js'; import type { CronSchedule, ScheduleSpec } from './types.js'; export const ONE_SECOND_MICROS = 1_000_000n; @@ -37,7 +37,7 @@ export function normalizeJobName(name: string): string { !JOB_NAME_PATTERN.test(normalized) ) { throw new CronInputError( - `${errors.invalidJobName}:use 1-48 lowercase snake_case characters` + `${internalErrors.invalidJobName}:use 1-48 lowercase snake_case characters` ); } return normalized; @@ -47,7 +47,7 @@ export function normalizeHistoryCap(value: number | undefined): number { const cap = value ?? 5; if (!Number.isSafeInteger(cap) || cap < 0 || cap > MAX_HISTORY_CAP) { throw new CronInputError( - `${errors.invalidHistoryCap}:must be an integer between 0 and ${MAX_HISTORY_CAP}` + `${internalErrors.invalidHistoryCap}:must be an integer between 0 and ${MAX_HISTORY_CAP}` ); } return cap; @@ -63,7 +63,7 @@ export function normalizeReconcileEverySeconds( value > MAX_INTERVAL_SECONDS ) { throw new CronInputError( - `${errors.invalidReconcileInterval}:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` + `${internalErrors.invalidReconcileInterval}:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` ); } return value; From ff2a196c847b03b85bf5a8a6c2ef47100c7246e9 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 12:53:13 -0400 Subject: [PATCH 26/32] Keep the retry unknown-handler code internal --- spacetime-retry-ts/README.md | 5 ++++- spacetime-retry-ts/scripts/test.ts | 2 +- spacetime-retry-ts/src/submodule.ts | 5 +++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md index 1a7cbd59e38..86c60ab0b55 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -89,7 +89,10 @@ view returns these attempts newest first. `reducers.removeRetryAdminIdentity` require a Retry admin. - `views.retryTasksAdmin` and `views.retryHistoryAdmin` return up to 1,000 pending tasks and attempts, newest first, to Retry admins. -- `errors` holds the `retry.*` codes thrown by these operations. +- `errors` holds the `retry.*` codes these operations throw as `SenderError`s: + `notAuthorized`, `invalidTaskName`, `invalidMaxAttempts`, + `invalidBackoffSeconds`, `taskAlreadyExists` (followed by `:` and the task + name), and `cannotRemoveLastAdmin`. The generated client can submit a task when the host exports `submitRetryTask`: diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts index 21e0138e733..ba5a6fb1276 100644 --- a/spacetime-retry-ts/scripts/test.ts +++ b/spacetime-retry-ts/scripts/test.ts @@ -200,7 +200,7 @@ assert.equal(tasks.size, 2); fire({ ...task, args: { tag: 'fails' } }); assert.equal(history.get(4n)?.error, 'unavailable'); fire({ ...task, args: { tag: 'toString' } }); -assert.equal(history.get(5n)?.error, `${errors.unknownHandler}:toString`); +assert.equal(history.get(5n)?.error, 'retry.unknown_handler:toString'); assert.equal(tasks.size, 4); // A SenderError gives up on the first attempt without scheduling another. diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts index 23dd7f2e1ee..1a77e6a89f2 100644 --- a/spacetime-retry-ts/src/submodule.ts +++ b/spacetime-retry-ts/src/submodule.ts @@ -19,6 +19,7 @@ const MAX_TASK_NAME_LENGTH = 128; const MAX_ERROR_LENGTH = 2048; const MAX_ROWS = 1000; +/** Codes a caller can receive as a `SenderError`. */ export const errors = { notAuthorized: 'retry.not_authorized', invalidTaskName: 'retry.invalid_task_name', @@ -26,7 +27,6 @@ export const errors = { invalidBackoffSeconds: 'retry.invalid_backoff_seconds', taskAlreadyExists: 'retry.task_already_exists', cannotRemoveLastAdmin: 'retry.cannot_remove_last_admin', - unknownHandler: 'retry.unknown_handler', } as const; function retryTaskTable(args: SumBuilder) { @@ -213,7 +213,8 @@ export function client({ try { const { tag } = arg.args; if (!Object.prototype.hasOwnProperty.call(handlers, tag)) { - throw new Error(`${errors.unknownHandler}:${tag}`); + // Only reachable when handlers bypass `RetryHandlers` typing. + throw new Error(`retry.unknown_handler:${tag}`); } result = handlers[tag](ctx, 'value' in arg.args ? arg.args.value : {}); } catch (error) { From 01c8fe59661fc7025bf77945f43141bb2667191a Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 13:23:35 -0400 Subject: [PATCH 27/32] Export resetRegisteredScopes from rate-limit --- spacetime-rate-limit-ts/README.md | 4 +++- spacetime-rate-limit-ts/scripts/test.ts | 6 ++++++ spacetime-rate-limit-ts/src/index.ts | 1 + spacetime-rate-limit-ts/src/limit.ts | 5 +++++ spacetime-rate-limit-ts/src/submodule.ts | 1 + 5 files changed, 16 insertions(+), 1 deletion(-) diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index d1c7044dde4..71c959b5f44 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -122,7 +122,9 @@ The view returns at most 1,000 rows and returns an empty set to non-admins. `client({ scope, limit, windowSeconds })` configures the policy for one scope. Each scope can be configured once per module; a second `client` call with the -same scope fails module loading with `rate_limit.duplicate_scope`. When a +same scope fails module loading with `rate_limit.duplicate_scope`. +`resetRegisteredScopes()` clears the configured scopes, for example between +tests that configure the same scope again. When a policy depends on application state, such as an upgrade tier, create one client per tier with its own scope. The returned limiter exposes `scope`, `limit`, and `windowSeconds`, plus: diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts index 4f8df94b90f..c2b87d900a2 100644 --- a/spacetime-rate-limit-ts/scripts/test.ts +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -4,6 +4,7 @@ import { client, errors, MAX_SWEEP_BATCH, + resetRegisteredScopes, sweepRateLimits, type RateLimitBucketRow, } from '../src/limit'; @@ -83,6 +84,11 @@ process.stdout.write('\nrate limiter\n'); 'rate_limit.duplicate_scope', 'a scope can be configured once' ); + resetRegisteredScopes(); + assert( + client({ scope: 'tap', windowSeconds: 30, limit: 5 }).limit === 5, + 'reset lets a scope be configured again' + ); assertThrows( () => tap.consume(tx, { key: '' }), errors.invalidActorKey, diff --git a/spacetime-rate-limit-ts/src/index.ts b/spacetime-rate-limit-ts/src/index.ts index d78b579d310..d9ec5496c38 100644 --- a/spacetime-rate-limit-ts/src/index.ts +++ b/spacetime-rate-limit-ts/src/index.ts @@ -1,6 +1,7 @@ export { client, errors, + resetRegisteredScopes, type RateLimitClient, type RateLimitPolicy, type RateLimitReadDb, diff --git a/spacetime-rate-limit-ts/src/limit.ts b/spacetime-rate-limit-ts/src/limit.ts index e658ee446e6..3437bc63d3a 100644 --- a/spacetime-rate-limit-ts/src/limit.ts +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -109,6 +109,11 @@ function secondsUntil(now: Timestamp, future: Timestamp): number { // evaluates it once in each fresh worker isolate. const registeredScopes = new Set(); +/** Forgets every configured scope so `client` can configure them again. */ +export function resetRegisteredScopes(): void { + registeredScopes.clear(); +} + /** * Configure the policy for one scope. Each scope may be configured once per * module so every caller enforces the same limit and window. diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts index 385d38d74c2..d485ce2c741 100644 --- a/spacetime-rate-limit-ts/src/submodule.ts +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -3,6 +3,7 @@ export { install } from './submodule/install.js'; export { client, errors, + resetRegisteredScopes, type RateLimitClient, type RateLimitPolicy, type RateLimitReadDb, From 44f4ed1339adfce4f84c34bf09c9aa689d8cfe1d Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Wed, 30 Sep 2026 14:29:52 -0400 Subject: [PATCH 28/32] Treat a signal-killed server as stopped in the cron recovery test --- spacetime-cron-ts/scripts/test-recovery.mjs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/spacetime-cron-ts/scripts/test-recovery.mjs b/spacetime-cron-ts/scripts/test-recovery.mjs index 33d8dc43b25..72d3a550790 100644 --- a/spacetime-cron-ts/scripts/test-recovery.mjs +++ b/spacetime-cron-ts/scripts/test-recovery.mjs @@ -164,12 +164,17 @@ function startServer() { return child; } +// A process killed by a signal reports signalCode and leaves exitCode null. +function hasExited(child) { + return child.exitCode !== null || child.signalCode !== null; +} + async function waitForServer(child) { await poll( 'isolated SpacetimeDB server', () => new Promise(resolve => { - if (child.exitCode !== null) { + if (hasExited(child)) { resolve(false); return; } @@ -185,13 +190,13 @@ async function waitForServer(child) { }); }) ); - if (child.exitCode !== null) { + if (hasExited(child)) { throw new Error(`isolated server exited early\n${serverLogs.at(-1)?.()}`); } } async function stopServer(child) { - if (!child || child.exitCode !== null) return; + if (!child || hasExited(child)) return; const exited = once(child, 'exit'); if (process.platform === 'win32') { spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { @@ -202,7 +207,7 @@ async function stopServer(child) { child.kill('SIGKILL'); } await Promise.race([exited, wait(5_000)]); - if (child.exitCode === null) { + if (!hasExited(child)) { throw new Error(`failed to stop isolated server process ${child.pid}`); } } From f9c855472e106a3705b43fd6441146e17991b0a9 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Thu, 1 Oct 2026 11:38:07 -0400 Subject: [PATCH 29/32] Explain core submodules through practical use cases --- spacetime-cron-ts/README.md | 65 +++++++++++-------------------- spacetime-crypto-ts/README.md | 16 ++++---- spacetime-rate-limit-ts/README.md | 23 +++++------ spacetime-retry-ts/README.md | 19 ++++----- 4 files changed, 48 insertions(+), 75 deletions(-) diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md index fe39857a1c3..b2316923a03 100644 --- a/spacetime-cron-ts/README.md +++ b/spacetime-cron-ts/README.md @@ -1,12 +1,12 @@ # @spacetimedb/cron -Calendar and interval scheduling for SpacetimeDB TypeScript modules. +Run recurring tasks in your SpacetimeDB application, such as daily reports, +scheduled cleanup, or periodic data updates. Choose a calendar schedule or a +fixed interval, pass arguments to each job, and inspect recent results. -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. +Schedules are stored in your database. Your application can change or cancel +them at runtime. Calendar schedules support time zones and daylight-saving +changes. ## Requirements @@ -27,27 +27,18 @@ npm install @spacetimedb/cron spacetimedb For the complete install, build, and publish workflow, see the repository's [Getting started guide](https://spacetimedb.com/docs/). -## Usage +## Quick start -### Integrate into an application +This module records a report each weekday at 9 AM in New York. Replace the +handler's database write with the work your application needs. ```ts import { schema, table, t } from 'spacetimedb/server'; import { client, cronTable } from '@spacetimedb/cron'; -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 dailyReport = cronTable({ name: 'daily_report' }); const cron = client({ - jobs: [dailyReport, heartbeat, refreshCatalog], - publicTables: true, + jobs: [dailyReport], reconcileEverySeconds: 300, }); @@ -64,26 +55,11 @@ export default spacetimedb; export const generateReport = dailyReport.cronReducer( spacetimedb, - (ctx, args, invocation) => { + (ctx, 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 => { - // Perform deterministic database work here. -}); - -export const refresh = refreshCatalog.cronProcedure( - spacetimedb, - (ctx, invocation) => { - // Use invocation.id as the idempotency key for an external request. - ctx.http.fetch('https://example.com/catalog'); } ); @@ -94,14 +70,21 @@ export const init = spacetimedb.init(ctx => { cron.schedule(ctx, dailyReport, '0 9 * * 1-5', { timezone: 'America/New_York', maxFailures: 3, - args: { workspaceId: 42n, format: 'summary' }, }); - cron.schedule(ctx, heartbeat, { everySeconds: 30 }); - cron.schedule(ctx, refreshCatalog, '0 */15 * * * *'); }); ``` -`init` seeds schedules for a fresh database. Runtime schedule changes remain database state across module publishes. +`init` creates the schedule for a new database. Later module publishes keep +schedule changes made at runtime. To run at a fixed interval instead, pass +`{ everySeconds: 30 }` in place of the cron expression. + +The repair sweep checks every five minutes for jobs that lost their next +scheduled run. Failure recovery is best effort; see [Execution model](#execution-model) +for crash behavior. `maxFailures: 3` disables the job after three consecutive +recorded failures. The `cronJobs` view lets clients subscribe to job status. + +See the [browser example](./example/) for jobs with arguments, HTTP requests, +and schedule controls. ## API @@ -382,8 +365,6 @@ 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-crypto-ts/README.md b/spacetime-crypto-ts/README.md index ae5053ce01e..c9b6e0f5712 100644 --- a/spacetime-crypto-ts/README.md +++ b/spacetime-crypto-ts/README.md @@ -1,8 +1,8 @@ # @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`. +Check that incoming webhooks came from Stripe, Resend, or GitHub before your +SpacetimeDB application acts on them. The package also provides SHA-256 hashing, +HMAC signatures, encoding helpers, and constant-time byte comparison. ## Install @@ -17,12 +17,8 @@ For the surrounding SpacetimeDB module workflow, see ### 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: +In your HTTP handler, verify a Stripe webhook with the raw request body and +the module's timestamp: ```ts import { SyncResponse } from 'spacetimedb/server'; @@ -44,6 +40,8 @@ tables and keep them out of public rows and procedure results. ## API +These helpers do not create database tables. Hashing uses `@noble/hashes`. + - `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. diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index 71c959b5f44..d125514edff 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -1,6 +1,11 @@ # @spacetimedb/rate-limit -Fixed-window rate limiter submodule for SpacetimeDB TypeScript modules. +Limit how often a user or service can perform an action in your SpacetimeDB +application. For example, allow each user to create 10 posts per minute. + +Choose a limit for each action, check it before doing the work, and report how +much capacity remains. Limits reset after a fixed time window, and expired +tracking records are cleaned up automatically. ## Install @@ -11,19 +16,12 @@ npm install @spacetimedb/rate-limit spacetimedb 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 -- configured limiter clients that consume and read buckets in host transactions -- a scheduled, bounded sweep of expired buckets -- admin-gated operations for diagnostics and maintenance - ## Usage ### Integrate into an application -Register the namespace, install its scheduled cleanup and admin state, then -consume from a limiter before performing the protected action: +Add Rate Limit to your module and initialize it. This example limits each user +to 10 posts per minute: ```ts import { schema, SenderError, t, table } from 'spacetimedb/server'; @@ -51,9 +49,8 @@ export const init = spacetimedb.init(ctx => { export default spacetimedb; ``` -Configure each policy once at module scope, then consume inside the same -transaction as the protected write. Derive the actor key from trusted request -or session state: +Configure the limit once, then check it in the same transaction that creates +the post. Use the caller's identity or authenticated user ID as the key: ```ts const postLimiter = rateLimit.client({ diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md index 86c60ab0b55..26542be7cd5 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -1,8 +1,9 @@ # @spacetimedb/retry -Typed retries for SpacetimeDB TypeScript modules. `client()` creates a private -scheduled-task table, attempt history, admin controls, and exponential-backoff -dispatch around handlers defined by the host module. +Retry failed background tasks in your SpacetimeDB application. Pass arguments +to a task, set an attempt limit, and choose how long to wait between attempts. +Each retry waits longer than the last, and administrators can inspect pending +tasks and past attempts. ## Install @@ -10,9 +11,6 @@ dispatch around handlers defined by the host module. npm install @spacetimedb/retry spacetimedb ``` -The tables and reducers are registered in the host schema. Retry 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. @@ -23,11 +21,10 @@ For the install-to-publish workflow, see ### Integrate into an application -Declare each task's argument type in `client()` when the module loads, before -`schema()`. Register the handlers with `retry.retryReducer()` after -`schema()`, so each handler receives the host's typed reducer context and its -task's typed arguments. The example below is a module-definition skeleton: -replace `sendReceipt` with an idempotent application function. +Define the task's arguments, add Retry's tables to your module, then register +the function that does the work. In this example, replace `sendReceipt` with +your application's function. It must be safe to run more than once for the +same order. ```ts import { schema, t } from 'spacetimedb/server'; From ce52d4c7541585aca76bbd215beceaa74aa4fdb7 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 2 Oct 2026 12:48:43 -0400 Subject: [PATCH 30/32] docs: simplify core submodule READMEs --- spacetime-cron-ts/README.md | 39 +--- spacetime-cron-ts/example/README.md | 210 +++++----------------- spacetime-crypto-ts/README.md | 18 +- spacetime-rate-limit-ts/README.md | 7 +- spacetime-rate-limit-ts/example/README.md | 200 ++++++--------------- spacetime-retry-ts/README.md | 15 +- 6 files changed, 116 insertions(+), 373 deletions(-) diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md index b2316923a03..54aa87e6dda 100644 --- a/spacetime-cron-ts/README.md +++ b/spacetime-cron-ts/README.md @@ -22,11 +22,6 @@ changes. 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/). - ## Quick start This module records a report each weekday at 9 AM in New York. Replace the @@ -83,8 +78,8 @@ scheduled run. Failure recovery is best effort; see [Execution model](#execution for crash behavior. `maxFailures: 3` disables the job after three consecutive recorded failures. The `cronJobs` view lets clients subscribe to job status. -See the [browser example](./example/) for jobs with arguments, HTTP requests, -and schedule controls. +See the [browser example](./example/) to change schedules and try a cleanup +job with arguments. ## API @@ -121,12 +116,6 @@ exactly one reducer or procedure for each handle after `schema()`. 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 host module's reducer context, inferred from `spacetimedb`, and a `CronInvocation`. Registration fails to compile if the schema does not include @@ -198,7 +187,7 @@ available for inspection. cron.unschedule(ctx, cleanup); ``` -These helpers perform scheduling operations. Application reducers remain responsible for authorization. +Application reducers must authorize schedule changes. Input errors from `cron.schedule()` are thrown as `SenderError`s. `errors` holds the codes a caller can receive at runtime, for example @@ -272,10 +261,7 @@ 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. +Recovery calls do not run the application handler. 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 @@ -296,9 +282,6 @@ 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 @@ -320,11 +303,11 @@ incompatible payload change, a new job name provides a clean version boundary. - 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. +- Spring-forward and fall-back behavior follows `cron-parser` 5.x. - 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. +A long-running procedure delays other scheduled work in the same module. ### Run history @@ -356,14 +339,8 @@ 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. +`test:module:local` requires a running local SpacetimeDB server. +`test:recovery` tests scheduled work across a host restart. ## License diff --git a/spacetime-cron-ts/example/README.md b/spacetime-cron-ts/example/README.md index 5119d5587a2..b7463c6f258 100644 --- a/spacetime-cron-ts/example/README.md +++ b/spacetime-cron-ts/example/README.md @@ -1,198 +1,82 @@ # Cron example -This example is a small browser dashboard backed directly by SpacetimeDB. It shows two jobs: +A dashboard for scheduling recurring tasks and viewing their results. -- `digest`, a weekday calendar job in `America/New_York` -- `cleanup`, a five-minute native interval job with a typed `keep` argument +The example starts with two tasks: -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. +- **Digest** adds a summary to the activity log at 9 AM on weekdays, New York time. +- **Cleanup** runs every five minutes and trims the activity log to its newest + 50 entries. You can change how many entries it keeps. -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. +## Run it locally -## What this demonstrates +Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from +this checkout. -- 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: +Start SpacetimeDB in a separate terminal: ```bash spacetime start ``` -From this directory: +From `spacetime-cron-ts/example`, run: ```bash pnpm install -pnpm --dir spacetimedb install -pnpm run build:module:fresh +pnpm run build:module pnpm run dev ``` -Open . +Open . The two tasks appear on the first publish. -`build:module:fresh` performs four steps: +## Try it -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. +1. Click **Schedule job** and select **Digest**. +2. Choose **Every 10 seconds**, then click **Schedule job** to save. +3. Wait for a run to appear. Each run adds an entry to the activity log. +4. Select **Cleanup**, choose **Every 10 seconds**, and set **Rows to keep** to + `3`. After enough digest runs, cleanup removes the older activity entries. +5. Click **Unschedule** on a task to stop it. Schedule it again to restart it. -After a module edit, preserve existing local data with: +You can set a fixed interval, such as every 30 seconds, or a calendar schedule, +such as weekdays at 9 AM. Saving a schedule replaces the previous one for that +task. Schedules keep running when you close the browser, as long as SpacetimeDB +is running. -```bash -pnpm run build:module -``` +## Change the example -## Use in your project +- [spacetimedb/src/index.ts](./spacetimedb/src/index.ts) defines the two tasks, + their starting schedules, and what each task does. +- [src/app.ts](./src/app.ts) connects the dashboard to SpacetimeDB and handles + the controls. -This workspace tests the submodule source in this repository. Consumer -applications install the published release: +After changing the server code, run `pnpm run build:module`. This keeps existing +data and schedules. Restart `pnpm run dev` after changing the browser code. -```bash -npm install @spacetimedb/cron spacetimedb -``` +To restore the starting schedules, run `pnpm run build:module:fresh`. **This +deletes all data in the local `spacetime-cron-example` database.** -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). +For instructions on adding scheduled tasks to your own app, see the +[Cron quick start](../README.md#quick-start). ## 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. `client()` 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 `cron.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 `cron.schedule()` and `cron.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 -``` +See [.env.example](./.env.example) to change the database address or web-server +port. The defaults work without a `.env` file. -`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. +## Before deploying -For a browser release check: +Anyone who connects to this example can change schedules and read the activity +and run history. Add permission checks and restrict access to that data before +using these controls in a public app. -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. +The example also checks for interrupted schedules every five minutes. For the +details of failed tasks and recovery, see +[Cron's execution model](../README.md#execution-model). ## 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. +- **Nothing runs:** the starting digest schedule only runs on weekday mornings. + Use **Every 10 seconds** to see a result sooner. +- **A task stops running:** check its recent failed runs before scheduling it + again. Repeated failures can disable a task. diff --git a/spacetime-crypto-ts/README.md b/spacetime-crypto-ts/README.md index c9b6e0f5712..7313d5d62b5 100644 --- a/spacetime-crypto-ts/README.md +++ b/spacetime-crypto-ts/README.md @@ -1,8 +1,7 @@ # @spacetimedb/crypto -Check that incoming webhooks came from Stripe, Resend, or GitHub before your -SpacetimeDB application acts on them. The package also provides SHA-256 hashing, -HMAC signatures, encoding helpers, and constant-time byte comparison. +Hash data, create HMAC signatures, and verify webhook signatures in SpacetimeDB. +The package also includes byte comparison and hex and base64 conversion helpers. ## Install @@ -10,12 +9,7 @@ HMAC signatures, encoding helpers, and constant-time byte comparison. npm install @spacetimedb/crypto ``` -For the surrounding SpacetimeDB module workflow, see -[Getting started](https://spacetimedb.com/docs/). - -## Usage - -### Integrate into an application +## Verify a webhook In your HTTP handler, verify a Stripe webhook with the raw request body and the module's timestamp: @@ -40,8 +34,6 @@ tables and keep them out of public rows and procedure results. ## API -These helpers do not create database tables. Hashing uses `@noble/hashes`. - - `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. @@ -52,8 +44,8 @@ These helpers do not create database tables. Hashing uses `@noble/hashes`. Resend webhooks. - `verifyGithubSignature(options)` verifies GitHub's SHA-256 webhook signature. -The verifiers return `{ ok: true }` or `{ ok: false, reason }`. `reason` is one -of the `errors` codes, so the caller decides what to log or return: +The verifiers return `{ ok: true }` or `{ ok: false, reason }`, with these +`errors` codes: | Code | Meaning | | ------------------------------------ | ------------------------------------------------------ | diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md index d125514edff..0015dc743c0 100644 --- a/spacetime-rate-limit-ts/README.md +++ b/spacetime-rate-limit-ts/README.md @@ -13,12 +13,7 @@ tracking records are cleaned up automatically. npm install @spacetimedb/rate-limit spacetimedb ``` -For the install-to-publish workflow, see -[Getting started](https://spacetimedb.com/docs/). - -## Usage - -### Integrate into an application +## Integrate into an application Add Rate Limit to your module and initialize it. This example limits each user to 10 posts per minute: diff --git a/spacetime-rate-limit-ts/example/README.md b/spacetime-rate-limit-ts/example/README.md index e28e0e71e8c..4e078a5d432 100644 --- a/spacetime-rate-limit-ts/example/README.md +++ b/spacetime-rate-limit-ts/example/README.md @@ -1,181 +1,85 @@ # 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. +A reactor game that shows how to limit repeated actions. Tap the reactor to +generate energy, buy upgrades, and watch what happens when you act too quickly. -## What this demonstrates +## Run it locally -- 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. +Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from +this checkout. -## Prerequisites +Start SpacetimeDB in a separate terminal: -- 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 +```bash spacetime start ``` -```powershell -spacetime server ping local -spacetime login show -``` - -## Quick start - -From `spacetime-rate-limit-ts/example`: +From `spacetime-rate-limit-ts/example`, run: -```powershell +```bash pnpm install -pnpm --dir spacetimedb install -node -e "require('node:fs').copyFileSync('.env.example', '.env')" -pnpm run build:module:fresh +pnpm run build:module pnpm run dev ``` -Open , start the reactor, and tap rapidly enough to fill -the tap bucket and heat meter. +Open . -`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. +## Try it -## Use in your project +1. Tap the reactor to generate energy. Watch **Tap Charges** decrease. +2. Keep tapping until you reach the limit. Wait for the charges to refill, then + tap again. +3. Watch the heat meter too. Overheating can stop your taps even when you have + charges left. Heat is a separate game rule. +4. Spend energy on upgrades and try the other actions. They have their own + limits and cooldowns. +5. Open the app in a private browser window to join as another player. Players + have separate tap limits, while the reactor and upgrade purchases are shared. -This workspace tests the submodule source in this repository. Consumer -applications install the published release: +## Change the example -```bash -npm install @spacetimedb/rate-limit spacetimedb -``` +- [spacetimedb/src/index.ts](./spacetimedb/src/index.ts) sets the limits and + checks them when a player acts. +- [spacetimedb/src/reactor-rules.ts](./spacetimedb/src/reactor-rules.ts) defines + the game rules and upgrades. +- [src/app.ts](./src/app.ts) connects the browser to SpacetimeDB. +- [public/ui.js](./public/ui.js) handles the game display and controls. -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 +After changing the server code, run `pnpm run build:module`. This keeps current +players and upgrades. Restart `pnpm run dev` after changing the browser code. -| 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. | +To start over, run `pnpm run build:module:fresh`. **This deletes all data in the +local `spacetime-rate-limit-example` database.** -The Node process serves static files, `GET /api/health`, and browser-safe -`GET /api/config`. Gameplay calls go directly from the browser to SpacetimeDB. +For instructions on limiting actions in your own app, see the +[Rate Limit integration guide](../README.md#integrate-into-an-application). -## Limiting model - -Each protected action has a limiter configured once with -`rateLimit.client({ scope, limit, windowSeconds })`. The host procedure calls -`limiter.consume(tx.as.rateLimit, { key })` inside its transaction with an actor -key derived from `ctx.sender`. The returned result includes remaining capacity, -reset time, and retry delay. The `reactor_limit_status` view reads the same -limiters with `limiter.peek(ctx.db.rateLimit, key)`. - -Tap Batteries and Upgrade Bay levels change the tap limit and the shop window. -Each level has its own limiter and scope (`reactor.tap.0`, `reactor.tap.1`, and so -on), so buying a level starts a fresh bucket. Those lanes are capped at the last -level that has a limiter. - -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. +## Configuration -The browser interpolates timers for presentation, but procedure responses and -subscribed server timestamps are authoritative. +See [.env.example](./.env.example) to change the database address or web-server +port. The defaults work without a `.env` file. -## Administration +## Optional admin controls -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: +The CLI identity that first publishes the database is its initial administrator. +To grant access to your browser identity, run this command while logged in as +that administrator. Replace `BROWSER_IDENTITY_HEX` with the connected browser's +identity: -```powershell +```bash spacetime call --server local spacetime-rate-limit-example rate_limit.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: +## Before deploying -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. +This game uses browser identities to distinguish players. In an app with user +accounts, connect the limits to those accounts so a user cannot get a fresh +allowance by opening a new browser session. Keep permission checks on the server; +rate limits do not decide who is allowed to perform an action. ## 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. +- **Taps are rejected:** check both **Tap Charges** and reactor heat. Either can + stop an action. +- **Debug data is empty:** grant your browser identity admin access using the + command above. diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md index 26542be7cd5..67594f5f858 100644 --- a/spacetime-retry-ts/README.md +++ b/spacetime-retry-ts/README.md @@ -14,12 +14,7 @@ npm install @spacetimedb/retry spacetimedb `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 +## Integrate into an application Define the task's arguments, add Retry's tables to your module, then register the function that does the work. In this example, replace `sendReceipt` with @@ -103,8 +98,8 @@ await conn.reducers.submitRetryTask({ }); ``` -Product-facing applications usually expose a narrower reducer that authorizes -the caller, fixes the retry limits, and calls `retry.submit`: +For user-facing operations, check permissions and set retry limits in a host +reducer: ```ts export const requestReceipt = db.reducer( @@ -121,8 +116,6 @@ export const requestReceipt = db.reducer( ); ``` -Operational screens can subscribe to the admin task and history views. - Package entrypoints: - `@spacetimedb/retry` exports `client`, `errors`, `retryOk`, `retryFailed`, @@ -137,8 +130,6 @@ pnpm run lint pnpm --dir spacetimedb run build ``` -The build compiles the fixture module that registers Retry's tables and reducers. - ## License Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). From 5fced67da297cbce9b96cee9d5ac8d2978c6a14e Mon Sep 17 00:00:00 2001 From: bradleyshep <148254416+bradleyshep@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:43:36 -0400 Subject: [PATCH 31/32] Add Resend transactional email submodule (#5904) # Description of Changes Adds a Resend submodule for sending transactional email and tracking delivery state in SpacetimeDB. - Synchronous procedures for outbound Resend requests and email operations. - Webhook signature verification, payload validation, idempotent ingestion, and replay. - Private delivery state and administrative configuration. - Package documentation, unit tests, and a dispatch example with generated client bindings. Builds on `bradley/submodules-core`. The package uses crypto; the example also uses rate-limit and shared example support. ## Example screenshots Existing example screenshots from #5823: ### Resend ![Resend example](https://github.com/user-attachments/assets/d13860fb-e4e9-481d-88a1-8f38c6a494ce) # API and ABI breaking changes No existing SpacetimeDB API or ABI is changed. This adds new TypeScript package APIs that need review before merge. # Rollback safety impact n/a. This adds opt-in TypeScript packages and examples; it does not change existing server storage formats. # Expected complexity level and risk **2/5** An isolated, opt-in Resend integration that does not change existing server behavior. For applications that use it, review delivery idempotency, webhook verification, and access to provider credentials. # Testing Verified locally on `bradley/submodules-email`: - [x] Frozen-lockfile install for the root, SDK, and present submodule workspaces. - [x] Type checks for the added packages. - [x] Existing test scripts for the added packages and examples. - [x] Build scripts for the added packages and examples. - [x] Regenerate client bindings and verify no tracked changes. - [x] Lint and formatting checks for the added packages and examples. - [x] Verify workspace dependencies are present in this branch. - [ ] Review the public email API, authorization, and webhook handling. - [ ] Run the Resend smoke test with credentials and a local SpacetimeDB instance. Commands used for this group: ```sh pnpm -r -F "./spacetime-resend-ts/**" run typecheck pnpm -r -F "./spacetime-resend-ts/**" run test pnpm -r -F "./spacetime-resend-ts/**" run build pnpm -r -F "./spacetime-resend-ts/**" run lint ``` The TypeScript SDK was built first. Live deployment and provider tests were not run during split validation. Existing workspace peer-dependency warnings remain. --- pnpm-lock.yaml | 130 +++ spacetime-resend-ts/.npmrc | 1 + spacetime-resend-ts/LICENSE.txt | 1 + spacetime-resend-ts/README.md | 243 +++++ spacetime-resend-ts/example/.env.example | 28 + spacetime-resend-ts/example/.npmrc | 1 + spacetime-resend-ts/example/README.md | 94 ++ spacetime-resend-ts/example/package.json | 30 + spacetime-resend-ts/example/public/index.html | 151 +++ spacetime-resend-ts/example/public/styles.css | 885 ++++++++++++++++++ .../example/scripts/test-message.ts | 15 + spacetime-resend-ts/example/server.ts | 237 +++++ .../example/spacetimedb/.npmrc | 1 + .../example/spacetimedb/package.json | 20 + .../example/spacetimedb/src/index.ts | 273 ++++++ .../example/spacetimedb/src/message.ts | 20 + .../example/spacetimedb/tsconfig.json | 15 + spacetime-resend-ts/example/src/app.ts | 673 +++++++++++++ .../clear_dispatches_procedure.ts | 19 + .../delete_dispatch_procedure.ts | 20 + .../example/src/module_bindings/index.ts | 242 +++++ .../my_dispatch_delivery_events_table.ts | 20 + .../my_dispatch_emails_table.ts | 46 + .../rateLimit/add_rate_limit_admin_reducer.ts | 15 + .../admin_rate_limit_buckets_table.ts | 20 + .../rateLimit/rate_limit_config_table.ts | 17 + .../remove_rate_limit_admin_reducer.ts | 15 + .../rateLimit/reset_buckets_reducer.ts | 15 + .../rateLimit/run_sweep_procedure.ts | 16 + .../src/module_bindings/rateLimit/types.ts | 44 + .../rateLimit/update_config_reducer.ts | 15 + .../resend/add_admin_identity_procedure.ts | 16 + .../resend/cancel_email_procedure.ts | 16 + .../resend/get_email_procedure.ts | 20 + .../get_resend_config_status_procedure.ts | 19 + .../resend/get_webhook_event_procedure.ts | 20 + .../resend/ingest_resend_webhook_reducer.ts | 19 + ...ist_delivery_events_for_email_procedure.ts | 20 + .../resend/list_emails_by_org_id_procedure.ts | 20 + .../resend/list_emails_by_status_procedure.ts | 23 + .../list_emails_by_user_id_procedure.ts | 20 + .../resend/remove_admin_identity_procedure.ts | 16 + .../resend/replay_webhook_event_reducer.ts | 15 + .../resend/resend_api_request_procedure.ts | 23 + .../resend/send_email_procedure.ts | 31 + .../resend/set_resend_config_procedure.ts | 18 + .../src/module_bindings/resend/types.ts | 124 +++ .../send_dispatch_procedure.ts | 22 + .../set_dispatch_policy_procedure.ts | 16 + .../example/src/module_bindings/types.ts | 97 ++ .../src/module_bindings/types/procedures.ts | 22 + .../src/module_bindings/types/reducers.ts | 10 + spacetime-resend-ts/example/tsconfig.json | 17 + spacetime-resend-ts/package.json | 86 ++ .../scripts/sys-abi-test-register.mjs | 27 + .../scripts/test-resend-smoke.ts | 602 ++++++++++++ spacetime-resend-ts/scripts/test-unit.ts | 98 ++ spacetime-resend-ts/scripts/test-webhooks.ts | 115 +++ spacetime-resend-ts/src/index.ts | 19 + spacetime-resend-ts/src/submodule.ts | 30 + spacetime-resend-ts/src/submodule/auth.ts | 67 ++ spacetime-resend-ts/src/submodule/config.ts | 108 +++ .../src/submodule/email-input.ts | 106 +++ .../src/submodule/email_writes.ts | 99 ++ spacetime-resend-ts/src/submodule/errors.ts | 44 + spacetime-resend-ts/src/submodule/http.ts | 68 ++ spacetime-resend-ts/src/submodule/install.ts | 9 + .../src/submodule/operations.ts | 370 ++++++++ spacetime-resend-ts/src/submodule/request.ts | 68 ++ spacetime-resend-ts/src/submodule/schema.ts | 283 ++++++ .../src/submodule/text-validation.ts | 7 + .../src/submodule/validation.ts | 32 + .../src/submodule/webhook-metadata.ts | 13 + spacetime-resend-ts/src/submodule/webhooks.ts | 402 ++++++++ spacetime-resend-ts/tsconfig.build.json | 10 + spacetime-resend-ts/tsconfig.json | 21 + 76 files changed, 6610 insertions(+) create mode 100644 spacetime-resend-ts/.npmrc create mode 120000 spacetime-resend-ts/LICENSE.txt create mode 100644 spacetime-resend-ts/README.md create mode 100644 spacetime-resend-ts/example/.env.example create mode 100644 spacetime-resend-ts/example/.npmrc create mode 100644 spacetime-resend-ts/example/README.md create mode 100644 spacetime-resend-ts/example/package.json create mode 100644 spacetime-resend-ts/example/public/index.html create mode 100644 spacetime-resend-ts/example/public/styles.css create mode 100644 spacetime-resend-ts/example/scripts/test-message.ts create mode 100644 spacetime-resend-ts/example/server.ts create mode 100644 spacetime-resend-ts/example/spacetimedb/.npmrc create mode 100644 spacetime-resend-ts/example/spacetimedb/package.json create mode 100644 spacetime-resend-ts/example/spacetimedb/src/index.ts create mode 100644 spacetime-resend-ts/example/spacetimedb/src/message.ts create mode 100644 spacetime-resend-ts/example/spacetimedb/tsconfig.json create mode 100644 spacetime-resend-ts/example/src/app.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/clear_dispatches_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/delete_dispatch_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/index.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/my_dispatch_delivery_events_table.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/my_dispatch_emails_table.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/add_rate_limit_admin_reducer.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/admin_rate_limit_buckets_table.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/rate_limit_config_table.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/remove_rate_limit_admin_reducer.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/reset_buckets_reducer.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/run_sweep_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/types.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/rateLimit/update_config_reducer.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/add_admin_identity_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/cancel_email_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/get_email_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/get_resend_config_status_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/get_webhook_event_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/ingest_resend_webhook_reducer.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/list_delivery_events_for_email_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_org_id_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_status_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_user_id_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/remove_admin_identity_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/replay_webhook_event_reducer.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/resend_api_request_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/send_email_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/set_resend_config_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/resend/types.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/send_dispatch_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/set_dispatch_policy_procedure.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/types.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/types/procedures.ts create mode 100644 spacetime-resend-ts/example/src/module_bindings/types/reducers.ts create mode 100644 spacetime-resend-ts/example/tsconfig.json create mode 100644 spacetime-resend-ts/package.json create mode 100644 spacetime-resend-ts/scripts/sys-abi-test-register.mjs create mode 100644 spacetime-resend-ts/scripts/test-resend-smoke.ts create mode 100644 spacetime-resend-ts/scripts/test-unit.ts create mode 100644 spacetime-resend-ts/scripts/test-webhooks.ts create mode 100644 spacetime-resend-ts/src/index.ts create mode 100644 spacetime-resend-ts/src/submodule.ts create mode 100644 spacetime-resend-ts/src/submodule/auth.ts create mode 100644 spacetime-resend-ts/src/submodule/config.ts create mode 100644 spacetime-resend-ts/src/submodule/email-input.ts create mode 100644 spacetime-resend-ts/src/submodule/email_writes.ts create mode 100644 spacetime-resend-ts/src/submodule/errors.ts create mode 100644 spacetime-resend-ts/src/submodule/http.ts create mode 100644 spacetime-resend-ts/src/submodule/install.ts create mode 100644 spacetime-resend-ts/src/submodule/operations.ts create mode 100644 spacetime-resend-ts/src/submodule/request.ts create mode 100644 spacetime-resend-ts/src/submodule/schema.ts create mode 100644 spacetime-resend-ts/src/submodule/text-validation.ts create mode 100644 spacetime-resend-ts/src/submodule/validation.ts create mode 100644 spacetime-resend-ts/src/submodule/webhook-metadata.ts create mode 100644 spacetime-resend-ts/src/submodule/webhooks.ts create mode 100644 spacetime-resend-ts/tsconfig.build.json create mode 100644 spacetime-resend-ts/tsconfig.json diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index eac067244b5..0bf8d497e0f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -555,6 +555,87 @@ importers: specifier: ^5.9.3 version: 5.9.3 + spacetime-resend-ts: + dependencies: + '@spacetimedb/crypto': + specifier: workspace:^ + version: link:../spacetime-crypto-ts + valibot: + specifier: ^1.4.2 + version: 1.5.0(typescript@5.9.3) + 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.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-resend-ts/example: + dependencies: + '@spacetimedb/example-ui': + specifier: workspace:* + version: link:../../spacetime-example-ui-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 + resend: + specifier: ^6.12.2 + version: 6.30.0 + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-resend-ts/example/spacetimedb: + dependencies: + '@spacetimedb/rate-limit': + specifier: workspace:* + version: link:../../../spacetime-rate-limit-ts + '@spacetimedb/resend': + 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': @@ -6418,6 +6499,9 @@ packages: '@speed-highlight/core@1.2.14': resolution: {integrity: sha512-G4ewlBNhUtlLvrJTb88d2mdy2KRijzs4UhnlrOSRT4bmjh/IqNElZa3zkrZ+TC47TwtlDWzVLFADljF1Ijp5hA==} + '@stablelib/base64@1.0.1': + resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==} + '@standard-schema/spec@1.0.0': resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==} @@ -9618,6 +9702,9 @@ packages: fast-npm-meta@0.4.8: resolution: {integrity: sha512-ybZVlDZ2PkO79dosM+6CLZfKWRH8MF0PiWlw8M4mVWJl8IEJrPfxYc7Tsu830Dwj/R96LKXfePGTSzKWbPJ08w==} + fast-sha256@1.3.0: + resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==} + fast-uri@3.1.0: resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} @@ -12268,6 +12355,9 @@ packages: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} + postal-mime@2.7.6: + resolution: {integrity: sha512-UUlyE2KlxmvwMGq060onF/VWU3zD6dVW31FwokQ5v26jWd35fbs2MoTFzh+jXnPwAyV2MULMKXcBInGOl5TO6Q==} + postcss-attribute-case-insensitive@7.0.1: resolution: {integrity: sha512-Uai+SupNSqzlschRyNx3kbCTWgY/2hcwtHEI/ej2LJWc9JJ77qKgGptd8DHwY1mXtZ7Aoh4z4yxfwMBue9eNgw==} engines: {node: '>=18'} @@ -13425,6 +13515,15 @@ packages: requires-port@1.0.0: resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} + resend@6.30.0: + resolution: {integrity: sha512-rED9rVw8N6cUvjmpYQwfZKBzd/cgWT+jURekVxtjFV2+YyK2/Tu2JOnE68sgqXlMBSYRoWgI6R0xlx3ANc/xeA==} + engines: {node: '>=20'} + peerDependencies: + '@react-email/render': '*' + peerDependenciesMeta: + '@react-email/render': + optional: true + reserved-identifiers@1.2.0: resolution: {integrity: sha512-yE7KUfFvaBFzGPs5H3Ops1RevfUEsDc5Iz65rOwWg4lE8HJSYtle77uul3+573457oHvBKuHYDl/xqUkKpEEdw==} engines: {node: '>=18'} @@ -13917,6 +14016,9 @@ packages: standard-as-callback@2.1.0: resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} + standardwebhooks@1.1.1: + resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==} + statuses@1.5.0: resolution: {integrity: sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==} engines: {node: '>= 0.6'} @@ -14830,6 +14932,14 @@ packages: typescript: optional: true + valibot@1.5.0: + resolution: {integrity: sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==} + peerDependencies: + typescript: '>=5' + peerDependenciesMeta: + typescript: + optional: true + validate-npm-package-license@3.0.4: resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==} @@ -21707,6 +21817,8 @@ snapshots: '@speed-highlight/core@1.2.14': {} + '@stablelib/base64@1.0.1': {} + '@standard-schema/spec@1.0.0': {} '@supabase/auth-js@2.97.0': @@ -26203,6 +26315,8 @@ snapshots: fast-npm-meta@0.4.8: {} + fast-sha256@1.3.0: {} + fast-uri@3.1.0: {} fastq@1.19.1: @@ -29758,6 +29872,8 @@ snapshots: possible-typed-array-names@1.1.0: {} + postal-mime@2.7.6: {} + postcss-attribute-case-insensitive@7.0.1(postcss@8.5.6): dependencies: postcss: 8.5.6 @@ -31057,6 +31173,11 @@ snapshots: requires-port@1.0.0: {} + resend@6.30.0: + dependencies: + postal-mime: 2.7.6 + standardwebhooks: 1.1.1 + reserved-identifiers@1.2.0: {} resolve-alpn@1.2.1: {} @@ -31674,6 +31795,11 @@ snapshots: standard-as-callback@2.1.0: {} + standardwebhooks@1.1.1: + dependencies: + '@stablelib/base64': 1.0.1 + fast-sha256: 1.3.0 + statuses@1.5.0: {} statuses@2.0.1: {} @@ -32649,6 +32775,10 @@ snapshots: optionalDependencies: typescript: 5.6.3 + valibot@1.5.0(typescript@5.9.3): + optionalDependencies: + typescript: 5.9.3 + validate-npm-package-license@3.0.4: dependencies: spdx-correct: 3.2.0 diff --git a/spacetime-resend-ts/.npmrc b/spacetime-resend-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-resend-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-resend-ts/LICENSE.txt b/spacetime-resend-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-resend-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-resend-ts/README.md b/spacetime-resend-ts/README.md new file mode 100644 index 00000000000..7ba61661644 --- /dev/null +++ b/spacetime-resend-ts/README.md @@ -0,0 +1,243 @@ +# @spacetimedb/resend + +Send email from your SpacetimeDB application through [Resend](https://resend.com). +Use it for welcome messages, receipts, and notifications, then track whether +each message was delivered, delayed, or bounced. + +The submodule stores delivery status in your database and updates it from +Resend webhooks. Your application decides who can send email and see its history. + +## Install + +```bash +npm install @spacetimedb/resend spacetimedb +``` + +Requires SpacetimeDB 2.8.3 or later for submodule mounting. + +## Integrate into an application + +Add Resend to your module and initialize it: + +```ts +import { schema } from 'spacetimedb/server'; +import * as resend from '@spacetimedb/resend/submodule'; + +const spacetimedb = schema({ resend }); +export default spacetimedb; + +export const init = spacetimedb.init(ctx => { + resend.install(ctx.as.resend); +}); +``` + +After publishing, configure your Resend API key, sender address, and webhook +signing secret as the database owner or a Resend administrator. When mounted +as `resend`, use `resend.set_resend_config`; the arguments are shown in +[Standalone configuration](#standalone-configuration). + +Call `resend.sendEmailRequest` from a procedure that checks who may send email +and which recipients they may contact. Apply rate limits before sending: + +```ts +resend.sendEmailRequest(ctx.as.resend, { + to: ['delivered@resend.dev'], + subject: 'Welcome', + html: '

Hello.

', + tagsJson: JSON.stringify([ + { name: 'userId', value: 'u_123' }, + { name: 'orgId', value: 'launch' }, + ]), +}); +``` + +For delivery updates, register `makeResendWebhookHandler()` on an HTTP route +and add that URL in Resend. See the [Dispatch example](./example/) for a +complete send procedure, webhook route, and views that show each user only +their own email history. + +### Standalone configuration + +When running Resend as its own database, configure it with the unprefixed +operation below. Credentials are private, and the publishing owner is the +first administrator. + +```bash +spacetime call --server http://127.0.0.1:3000 spacetime-resend set_resend_config \ + '"re_..."' \ + '{"some":"whsec_..."}' \ + '{"some":"onboarding@resend.dev"}' +``` + +Args: `apiKey`, `webhookSigningSecret` (required for webhook ingest), `defaultFrom` (optional). +For `t.option(...)` CLI arguments, use `null` for no value and +`{"some":"value"}` for a string value. + +Verify: + +```bash +spacetime call --server http://127.0.0.1:3000 spacetime-resend get_resend_config_status '{}' +``` + +## Private tables + +| Table | Key | Notes | +| ----------------------- | ----------- | ------------------------------------------------------------ | +| `resend_email` | `resend_id` | one row per outbound email; `status` reflects latest webhook | +| `resend_delivery_event` | `event_id` | append-only audit log of every event for an email | + +- `resend_webhook_event` - idempotency log +- `resend_config` - credentials singleton +- `resend_admin_identity` - admin allowlist + +None of the Resend base tables are subscribable. Email recipients, subject, +body, tracking state, webhook payloads, and signature headers remain private. +Host modules should expose caller- or tenant-scoped views over `userId` or +`orgId`; the included example demonstrates this pattern. + +## API + +**Setup** + +- `set_resend_config(apiKey, webhookSigningSecret, defaultFrom)` +- `get_resend_config_status()` - `{ isConfigured, hasWebhookSecret, apiKeyLength, ... }` +- `add_admin_identity(identity)` / `remove_admin_identity(identity)` + +**Outbound** + +- `send_email({ from, to, subject, html, text, cc, bcc, replyTo, tagsJson, headersJson, scheduledAt, idempotencyKey})` - admin-gated; inserts a `resend_email` row with `status = queued`, returns `{ resendId }`. The first webhook flips it to `sent`/`delivered`. +- `cancel_email({ resendId })` - admin-gated +- `resend_api_request({ method, path, jsonBody, idempotencyKey })` - admin-gated + request to a relative `api.resend.com` path; accepted methods are `GET`, `POST`, + `PATCH`, and `DELETE` + +Email sends accept up to 100 combined `to`, `cc`, and `bcc` recipients. Address +fields are capped at 320 characters, subjects at 998 characters, HTML and text +at 200,000 characters each, and tag or header JSON at 16 KiB. Control characters +in address, subject, and schedule fields are rejected before provider HTTP. + +The generated client calls your application's send procedure, such as the +`sendDispatch` procedure in the example: + +```ts +const result = await conn.procedures.sendDispatch({ + to: 'delivered@resend.dev', + subject: 'Welcome', + message: 'Your workspace is ready.', +}); + +if (!result.ok) throw new Error(result.message); +``` + +Subscribe to a caller-scoped host view for delivery status. Keep the private +Resend tables and generic administrative send operation restricted to +operators. + +**Webhook ingest / replay** + +- `ingest_resend_webhook(eventId, eventType, payloadJson, signatureHeader, timestampHeader)` - deduplicates events by the `svix-id` header passed as `eventId` +- `replay_webhook_event(eventId)` - re-applies a stored event +- `makeResendWebhookHandler()` builds a direct HTTP webhook handler for a host + router. + +The HTTP handler returns 200 after applying an event, for an already processed +event, and for signed event types the submodule does not handle, which are stored +as `Ignored`. Invalid payloads return 400 and retain a failed event record; +redelivery retries failed records. Unexpected transaction failures propagate to +the HTTP runtime. + +The reducer throws, writing nothing, when metadata, size, headers, secret, or +signature checks reject a request. Once a signed event is stored, the reducer +commits: an invalid payload keeps its `Failed` event record with the error +message. Callers read the outcome with `get_webhook_event`. + +Delivery timestamps use the provider's event time. Older events cannot replace +newer status, and an earlier delivery stage cannot replace a later one. Queued +send responses preserve any webhook state already recorded. Opens, clicks, and +complaints update their own fields without changing delivery status. Error, +bounce, and failure details change only when their event sets the status. + +**Admin queries** + +- `get_email`, `list_emails_by_user_id`, `list_emails_by_org_id`, `list_emails_by_status` +- `list_delivery_events_for_email` +- `get_webhook_event` - stored event with `status` (`Received`, `Processed`, + `Ignored`, or `Failed`) and `errorMessage` + +List procedures return at most 1,000 rows. Host applications should expose +caller-scoped, paginated views for product-facing history. + +**Errors** + +`errors` from `@spacetimedb/resend/submodule` lists the `resend.*` codes the +submodule throws. + +Package entrypoints: + +- `@spacetimedb/resend` can run as a standalone email database. +- `@spacetimedb/resend/submodule` supplies submodule configuration, delivery, + webhook, and query helpers. + +## Webhook events handled + +``` +email.sent email.delivered +email.delivery_delayed email.bounced +email.complained email.failed +email.opened email.clicked +``` + +Other signed event types, such as `email.received`, `contact.*`, and `domain.*`, +are acknowledged and stored as `Ignored`. + +`opened` / `clicked` / `complained` are recorded as **flags + timestamps** and leave `status` unchanged. Terminal states (`delivered`, `bounced`, `failed`, `cancelled`) and in-flight states (`queued`, `sent`, `delivery_delayed`) live in the `status` column. + +## Webhook signature verification + +The `ingest_resend_webhook` reducer and the `makeResendWebhookHandler()` route verify Standard Webhooks signatures (svix) using the configured `webhookSigningSecret`. A rejected signature returns 401 with `resend.webhook_signature_mismatch:`, where the reason is a `@spacetimedb/crypto` `errors` code such as `crypto.timestamp_outside_tolerance`. `signatureHeader` and `timestampHeader` are stored on `resend_webhook_event` for forensic replay. + +## Tagging + +`userId` / `orgId` are extracted from Resend `tags` and indexed for per-user / per-org listing. + +- `send_email` takes `tagsJson` as a JSON string in the array form Resend's send API expects: `[{"name":"userId","value":"u_123"}]`. +- Resend webhook payloads carry tags in object form: `{"userId": "u_123", "orgId": "o_456"}`. + +## Integration testing + +```bash +# Build + publish + event paths, idempotency, replay, signed-type checks, and authorization checks +pnpm run test:smoke +``` + +The smoke test publishes only to the dedicated `resend-ts-smoke-test` database. + +For real Resend test-mode: + +```bash +# Bootstrap once with your real key: +spacetime call --server http://127.0.0.1:3000 spacetime-resend set_resend_config '"re_..."' null '{"some":"onboarding@resend.dev"}' + +# Then send to one of Resend's test addresses (delivered@/bounced@/complained@): +spacetime call --server http://127.0.0.1:3000 spacetime-resend send_email \ + null \ + '["delivered@resend.dev"]' \ + '"Test from SpacetimeDB"' \ + '{"some":"

Hello.

"}' \ + null null null null \ + '{"some":"[{\"name\":\"userId\",\"value\":\"u_123\"}]"}' \ + null null null +``` + +The standalone module has no HTTP route. To receive webhooks from Resend, mount the submodule in a host module that registers `makeResendWebhookHandler()` on a router, as the [example](./example/spacetimedb/) does at `/webhook/resend`. Expose the database through a public tunnel such as ngrok and register `https:///v1/database//route/webhook/resend` in Resend's dashboard with the same `whsec_...` you passed to `set_resend_config`. + +## Testing + +```bash +pnpm test +pnpm run lint +``` + +## License + +Apache-2.0. diff --git a/spacetime-resend-ts/example/.env.example b/spacetime-resend-ts/example/.env.example new file mode 100644 index 00000000000..c162013b626 --- /dev/null +++ b/spacetime-resend-ts/example/.env.example @@ -0,0 +1,28 @@ +# Copy to .env. The example server loads this on startup. + +# ---------------- Resend ---------------- +# Required to send email from Dispatch. +RESEND_API_KEY=re_... + +# Required to accept inbound webhooks (Resend dashboard, Webhooks -> your endpoint -> Signing secret). +# The module rejects requests when this is unset or the signature is invalid. +RESEND_WEBHOOK_SECRET=whsec_... + +# Optional comma-separated external recipients. Provider test recipients remain +# available automatically. The module rejects every address outside this list. +RESEND_ALLOWED_RECIPIENTS=you@example.com + +# ---------------- SpacetimeDB ---------------- +STDB_URI=ws://127.0.0.1:3000 +STDB_HTTP=http://127.0.0.1:3000 +SPACETIMEDB_DB_NAME=spacetime-resend-example +# Optional. When unset, the server creates a persistent local identity token in +# .stdb-server-token and the logged-in publishing identity authorizes it. +# STDB_SERVER_TOKEN= + +# ---------------- Static server ---------------- +PORT=8790 +HOST=127.0.0.1 + +# Default "from" address (must be a verified sender in your Resend account, or onboarding@resend.dev for testing). +DEFAULT_FROM=onboarding@resend.dev diff --git a/spacetime-resend-ts/example/.npmrc b/spacetime-resend-ts/example/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-resend-ts/example/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-resend-ts/example/README.md b/spacetime-resend-ts/example/README.md new file mode 100644 index 00000000000..562dbb2de2f --- /dev/null +++ b/spacetime-resend-ts/example/README.md @@ -0,0 +1,94 @@ +# Dispatch email example + +Send an email with Resend and watch its delivery status update in the app. + +## Run it locally + +Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from +this checkout. + +Start SpacetimeDB in a separate terminal: + +```bash +spacetime start +``` + +From `spacetime-resend-ts/example`, copy [.env.example](./.env.example) to `.env`. + +You also need a Resend API key. In `.env`, replace `RESEND_API_KEY` with your +key. Leave `RESEND_WEBHOOK_SECRET` empty until you set up a webhook below. +Remove the sample `RESEND_ALLOWED_RECIPIENTS` address or replace it with an +address you control. + +Then publish the example and start its web server: + +```bash +pnpm install +pnpm run build:module +pnpm run dev +``` + +Open . + +## Try it + +1. Click **Delivered** to use Resend's test recipient. +2. Write a subject and message, then send the email. +3. The message appears in the list. To see it change to Delivered, complete + the webhook setup below. +4. Try the **Bounced** and **Complaint** test recipients to see other outcomes. + +To send to a real address, add it to +`RESEND_ALLOWED_RECIPIENTS` and restart the example server. Use a sender that +Resend permits for your account; `DEFAULT_FROM` starts as +`onboarding@resend.dev`. + +## Receive delivery updates + +1. Use a tunnel to expose the example's `/webhook/resend` route. +2. Add that public URL as a webhook endpoint in Resend and select the email + events you want to receive. +3. Copy the endpoint's signing secret into `RESEND_WEBHOOK_SECRET`. +4. Restart `pnpm run dev` and send another test email. + +The local route is `http://127.0.0.1:8790/webhook/resend`. You can also forward +directly to the database route: + +```text +http://127.0.0.1:3000/v1/database/spacetime-resend-example/route/webhook/resend +``` + +The app rejects webhook requests with a missing or invalid signature. +Without a reachable webhook, email status stays Queued. + +## Before deploying + +Anyone who can open this demo can send to the allowed recipients. It limits +each browser identity to five sends per ten minutes and all users to 25 per +hour. Add account-based access checks before making the app public. Expose +only the webhook route when testing through a tunnel. + +The server saves its admin credential in `.stdb-server-token`. Keep that file +and `.env` private. + +## Troubleshooting + +- **Sending fails:** check the API key, allowed recipients, and sender address. +- **Status stays Queued:** check the public webhook URL and signing secret. +- **`resend.not_authorized`:** use the CLI account that published the database, + then restart the example server. + +## Change the example + +- [spacetimedb/src/index.ts](./spacetimedb/src/index.ts): email sending and delivery updates. +- [server.ts](./server.ts): Resend setup and webhook forwarding. +- [src/app.ts](./src/app.ts): email form and message list. + +After changing server code, run `pnpm run build:module`. Restart +`pnpm run dev` after changing browser code or `.env`. + +To start over, run `pnpm run build:module:fresh`. **This deletes all data in +the local `spacetime-resend-example` database.** + +To use the submodule in your own app, see the +[package integration guide](../README.md#integrate-into-an-application). diff --git a/spacetime-resend-ts/example/package.json b/spacetime-resend-ts/example/package.json new file mode 100644 index 00000000000..2dc1f7f6aa2 --- /dev/null +++ b/spacetime-resend-ts/example/package.json @@ -0,0 +1,30 @@ +{ + "name": "spacetime-resend-example", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings --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-message.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/example-ui": "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", + "resend": "^6.12.2", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-resend-ts/example/public/index.html b/spacetime-resend-ts/example/public/index.html new file mode 100644 index 00000000000..c788c2ea747 --- /dev/null +++ b/spacetime-resend-ts/example/public/index.html @@ -0,0 +1,151 @@ + + + + + + + Dispatch + + + +
+
+
+ +
+

Dispatch

+ Send an email, watch its delivery resolve live +
+
+
+ +
+
+
+

Compose

+

+ Dispatched through the mounted Resend submodule. +

+
+ +
+ + +
+
+ Message +
+ + +
+
+ + +
+ +
+
+ +
+ Resend test addresses +
+ + + +
+
+
+ +
+
+
+

Live delivery

+

+ Every dispatch and its lifecycle, streamed from SpacetimeDB. +

+
+
+ 0 sent + +
+
+ +
+
+ 0Sent +
+
+ 0Delivered +
+
+ 0Opened +
+
+ 0Bounced +
+
+ +
+
+
+ +
+ Built on + SpacetimeDB +
+
+ + + + diff --git a/spacetime-resend-ts/example/public/styles.css b/spacetime-resend-ts/example/public/styles.css new file mode 100644 index 00000000000..91cc3c7532b --- /dev/null +++ b/spacetime-resend-ts/example/public/styles.css @@ -0,0 +1,885 @@ +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500;600&display=swap'); + +:root { + /* Tokens from spacetimedb.com/app/styles/variables.css */ + --font-inter: 'Inter', ui-sans-serif, system-ui, -apple-system, sans-serif; + --font-ibm: 'IBM Plex Mono', ui-monospace, monospace; + + --color-green: #4cf490; + --color-green-10: #4cf4901a; + --color-green-20: #4cf49033; + --color-white: #d7d8d9; + --color-yellow: #fbdc8e; + --color-purple: #a880ff; + --color-orange: #ff9e9e; + --color-blue: #02befa; + --color-pink: #ff80fb; + --color-teal: #00ccb4; + --color-red: #ff4c4c; + + --color-n1: #e6e9f0; + --color-n2: #ced3e0; + --color-n3: #b6c0cf; + --color-n4: #6f7987; + --color-n5: #363840; + --color-n8: #060606; + + --color-shade1: #162d38; + --color-shade4: #121e24; + --color-shade5: #0f191f; + --color-shade6: #0e161a; + --color-shade7: #0b1114; + --color-shade8: #0b0e12; + + --radius-sm: 6px; + --radius: 10px; + --radius-lg: 14px; +} + +* { + box-sizing: border-box; +} +html, +body { + margin: 0; + min-height: 100%; +} +body { + color: var(--color-white); + background: var(--color-shade7); + font-family: var(--font-inter); + -webkit-font-smoothing: antialiased; +} +::selection { + background: var(--color-green); + color: var(--color-n8); +} +a { + color: var(--color-green); + text-decoration: none; +} + +* { + scrollbar-width: thin; + scrollbar-color: var(--color-shade4) transparent; +} +*::-webkit-scrollbar { + width: 6px; + height: 6px; +} +*::-webkit-scrollbar-track { + background: transparent; +} +*::-webkit-scrollbar-thumb { + background: var(--color-shade4); + border-radius: 3px; +} +*::-webkit-scrollbar-thumb:hover { + background: var(--color-shade1); +} + +button, +input, +textarea { + font: inherit; +} +button { + height: 34px; + padding: 0 16px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: var(--color-shade7); + color: var(--color-n2); + font-family: var(--font-inter); + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: + background 0.18s, + border-color 0.18s, + color 0.18s; +} +button:hover:not(:disabled) { + background: var(--color-shade4); + color: var(--color-white); +} +button:focus-visible { + outline: 2px solid var(--color-green); + outline-offset: 2px; +} +button.primary { + background: var(--color-n3); + border-color: var(--color-n3); + color: var(--color-n8); +} +button.primary:hover:not(:disabled) { + background: var(--color-white); + border-color: var(--color-white); + color: var(--color-n8); +} +button.primary:active:not(:disabled) { + background: var(--color-green); + border-color: var(--color-green); +} +button.primary.sent { + background: var(--color-green); + border-color: var(--color-green); + color: var(--color-n8); + opacity: 1; +} +button:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +input, +textarea { + width: 100%; + padding: 10px 12px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: var(--color-shade8); + color: var(--color-white); + outline: none; + transition: + border-color 0.15s, + box-shadow 0.15s; +} +input { + height: 40px; + padding: 0 12px; +} +textarea { + min-height: 120px; + resize: none; + line-height: 1.5; + font-size: 14px; +} +input::placeholder, +textarea::placeholder { + color: var(--color-n4); +} +input:focus, +textarea:focus { + border-color: var(--color-green); + box-shadow: 0 0 0 3px var(--color-green-10); +} +label { + display: grid; + gap: 7px; + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + letter-spacing: 0.07em; + text-transform: uppercase; +} +h1, +h2, +h3, +p { + margin: 0; +} +.muted { + color: var(--color-n4); +} + +.shell { + width: min(1200px, calc(100% - 32px)); + margin: 0 auto; + padding: 16px 0 0; + /* Viewport height gives the feed its own scroll area. Mobile uses auto + height in the media query. */ + height: 100vh; + display: flex; + flex-direction: column; +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + border: 1px solid #17303b; + border-radius: var(--radius-lg); + background: linear-gradient(180deg, #0d1920, #0b1319); + box-shadow: inset 0 1px 0 #26435166; + padding: 11px 16px; + margin-bottom: 14px; +} +.brand { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; +} +.brand-mark { + flex: 0 0 auto; + width: 34px; + height: 34px; + border-radius: var(--radius); + display: grid; + place-items: center; + color: var(--color-green); + background: var(--color-green-10); + border: 1px solid var(--color-green-20); +} +.brand-mark svg { + width: 18px; + height: 18px; +} +.brand-text { + display: grid; + gap: 1px; + min-width: 0; +} +.brand-text h1 { + margin: 0; + font-size: 15px; + font-weight: 700; + line-height: 1.2; + color: var(--color-n1); +} +.brand-sub { + color: var(--color-n4); + font-size: 12px; +} + +.workspace { + flex: 1; + display: grid; + grid-template-columns: 372px minmax(0, 1fr); + /* One row that is at least 520px and otherwise fills the viewport, so both + panels are always equal height and grow when the window grows. */ + grid-template-rows: minmax(520px, 1fr); + gap: 14px; + align-items: stretch; + min-height: 0; + margin-bottom: 16px; +} +.panel { + border: 1px solid var(--color-shade4); + border-radius: var(--radius-lg); + background: linear-gradient(180deg, var(--color-shade5), var(--color-shade6)); +} + +/* Compose */ +.compose { + padding: 18px; + display: flex; + flex-direction: column; + gap: 16px; +} +.compose-head { + display: grid; + gap: 3px; +} +.compose-head h2 { + font-size: 15px; + font-weight: 700; + color: var(--color-n1); +} +.compose-head p { + font-size: 13px; +} +.form-grid { + display: flex; + flex-direction: column; + gap: 13px; + flex: 1; + min-height: 0; +} +.form-grid > button.primary { + height: 42px; + font-size: 14px; +} +.field { + display: flex; + flex-direction: column; + gap: 7px; + flex: 1; + min-height: 0; +} +.field textarea, +.field .mail-preview { + flex: 1; + min-height: 120px; +} + +.test-block { + display: grid; + gap: 9px; +} +.test-label { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + letter-spacing: 0.07em; + text-transform: uppercase; +} +.test-row { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; +} +.test-row button { + min-width: 0; + height: 32px; + padding: 0 6px; + font-size: 12px; +} +.test-row button b { + display: block; + font-size: 12px; + font-weight: 600; + color: var(--color-n2); +} + +/* Message field with write/preview tabs */ +.field-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; +} +.field-label { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + letter-spacing: 0.07em; + text-transform: uppercase; +} +.msg-tabs { + display: inline-flex; + gap: 2px; + padding: 2px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: var(--color-shade8); +} +.msg-tab { + height: 24px; + padding: 0 12px; + border: 0; + border-radius: 4px; + background: transparent; + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} +.msg-tab:hover:not(.active) { + background: transparent; + color: var(--color-n2); +} +.msg-tab.active { + background: var(--color-shade4); + color: var(--color-n1); +} + +.mail-preview { + min-height: 128px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: #ffffff; + overflow: hidden; +} +.mp-head { + padding: 12px 14px; + border-bottom: 1px solid #e6e8ec; + background: #f6f7f9; +} +.mp-subject { + font-size: 14px; + font-weight: 600; + color: #1f2933; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.mp-from { + margin-top: 3px; + font-size: 12px; + color: #6b7280; +} +.mp-body { + padding: 14px; + font-size: 14px; + color: #1f2933; + line-height: 1.6; + word-break: break-word; +} +.mp-body .mp-empty { + color: #9aa3af; + font-style: italic; +} + +.form-error { + color: var(--color-orange); + font-family: var(--font-ibm); + font-size: 12px; + line-height: 1.4; +} +.form-error:empty { + display: none; +} + +/* Live delivery console */ +.console { + display: grid; + grid-template-rows: auto auto minmax(0, 1fr); + min-height: 0; +} +.console-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + padding: 16px 18px; + border-bottom: 1px solid var(--color-shade4); +} +.console-copy { + display: grid; + gap: 3px; +} +.console-copy h2 { + font-size: 15px; + font-weight: 700; + color: var(--color-n1); +} +.console-copy p { + font-size: 13px; +} +.console-right { + display: flex; + align-items: center; + gap: 12px; +} +.feed-count { + color: var(--color-n5); + font-family: var(--font-ibm); + font-size: 11px; +} +#clear-btn { + height: 30px; + padding: 0 12px; + font-size: 12px; +} +#clear-btn:disabled { + opacity: 0.4; +} + +.metrics { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 10px; + padding: 16px 18px; + border-bottom: 1px solid var(--color-shade4); +} +.metric { + display: grid; + gap: 7px; + padding: 13px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius); + background: var(--color-shade7); +} +.metric strong { + font-size: 25px; + font-weight: 700; + line-height: 1; + color: var(--color-white); + font-variant-numeric: tabular-nums; +} +.metric span { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + letter-spacing: 0.06em; + text-transform: uppercase; +} +.metric.delivered strong { + color: var(--color-green); +} +.metric.opened strong { + color: var(--color-green); +} +.metric.bounced strong { + color: var(--color-red); +} + +.feed { + min-height: 0; + overflow-y: auto; + padding: 14px 18px 18px; + display: grid; + gap: 11px; + align-content: start; +} + +.mail { + border: 1px solid var(--color-shade4); + border-radius: var(--radius); + background: var(--color-shade7); + padding: 14px 15px 16px; + transition: border-color 0.15s; +} +.mail:hover { + border-color: var(--color-shade1); +} +.mail.bad { + border-color: #4a2626; +} +.mail-head { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto auto; + gap: 11px; + align-items: center; +} +.mail-del { + width: 26px; + height: 26px; + padding: 0; + flex: 0 0 auto; + border: 1px solid transparent; + border-radius: var(--radius-sm); + background: transparent; + color: var(--color-n5); + font-size: 17px; + line-height: 1; + display: grid; + place-items: center; +} +.mail-del:hover:not(:disabled) { + background: #1a0f0f; + border-color: #4a2626; + color: var(--color-red); +} +.avatar { + width: 36px; + height: 36px; + flex: 0 0 auto; + border-radius: var(--radius); + display: grid; + place-items: center; + font-weight: 700; + font-size: 12px; + color: var(--av, var(--color-n3)); + background: color-mix(in srgb, var(--av, #555) 15%, transparent); + border: 1px solid color-mix(in srgb, var(--av, #555) 32%, transparent); +} +.mail-who { + min-width: 0; +} +.mail-to { + font-size: 14px; + color: var(--color-n1); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.mail-sub { + margin-top: 2px; + font-size: 13px; + color: var(--color-n4); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.mail-when { + flex: 0 0 auto; + text-align: right; + color: var(--color-n5); + font-family: var(--font-ibm); + font-size: 11px; +} + +/* Delivery timeline */ +.track { + display: flex; + margin-top: 15px; +} +.node { + flex: 1; + position: relative; + text-align: center; + min-width: 0; +} +.node::before { + content: ''; + position: absolute; + top: 6px; + left: -50%; + width: 100%; + height: 2px; + background: var(--color-shade4); +} +.node:first-child::before { + display: none; +} +.bead { + position: relative; + z-index: 1; + display: block; + width: 14px; + height: 14px; + margin: 0 auto; + border-radius: 50%; + background: var(--color-shade4); + border: 2px solid var(--color-shade6); +} +.node-label { + display: block; + margin-top: 7px; + font-family: var(--font-ibm); + font-size: 10px; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--color-n5); +} +.node-time { + display: block; + margin-top: 2px; + font-family: var(--font-ibm); + font-size: 10px; + color: var(--color-n5); + min-height: 12px; +} + +.node.done::before { + background: var(--color-green); +} +.node.done .bead { + background: var(--color-green); + box-shadow: 0 0 0 3px var(--color-green-10); +} +.node.done .node-label { + color: var(--color-n2); +} +.node.done .node-time { + color: var(--color-n4); +} + +.node.live::before { + background: var(--color-green); +} +.node.live .bead { + background: var(--color-green); + box-shadow: 0 0 0 5px color-mix(in srgb, var(--color-green) 26%, transparent); + animation: live-pulse 1.8s ease-in-out infinite; +} +.node.live .node-label { + color: var(--color-green); +} + +.node.bad::before { + background: var(--color-red); +} +.node.bad .bead { + background: var(--color-red); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-red) 20%, transparent); +} +.node.bad .node-label { + color: var(--color-red); +} + +.node.warn::before { + background: var(--color-yellow); +} +.node.warn .bead { + background: var(--color-yellow); +} +.node.warn .node-label { + color: var(--color-yellow); +} + +/* One-shot: the node that just reached its state ripples out from the bead. + Applied only to the node that changed this render. */ +.node.just-lit .bead::after { + content: ''; + position: absolute; + inset: -3px; + border-radius: 50%; + border: 2px solid var(--color-green); + animation: bead-ripple 0.65s ease-out forwards; +} +.node.just-lit.bad .bead::after { + border-color: var(--color-red); +} +.node.just-lit.warn .bead::after { + border-color: var(--color-yellow); +} +.node.just-lit::before { + animation: connector-sweep 0.5s ease-out; +} +.node.just-lit .node-label, +.node.just-lit .node-time { + animation: label-in 0.5s ease-out; +} + +.mail.card-enter { + animation: card-enter 0.4s cubic-bezier(0.2, 0.8, 0.2, 1); +} +/* Odometer roll: the current number exits as the incoming value enters. + JavaScript injects the clip window for the animation. */ +.metric strong .odo-clip { + display: block; + overflow: hidden; + height: 1em; +} +.metric strong .odo { + display: block; +} +.metric strong .odo-line { + height: 1em; + line-height: 1; +} +.metric strong .odo.roll-up { + animation: odo-up 0.42s cubic-bezier(0.3, 0.9, 0.3, 1) forwards; +} +.metric strong .odo.roll-down { + animation: odo-down 0.42s cubic-bezier(0.3, 0.9, 0.3, 1) forwards; +} + +@keyframes live-pulse { + 0%, + 100% { + box-shadow: 0 0 0 5px + color-mix(in srgb, var(--color-green) 26%, transparent); + } + 50% { + box-shadow: 0 0 0 8px color-mix(in srgb, var(--color-green) 8%, transparent); + } +} +@keyframes bead-ripple { + 0% { + transform: scale(1); + opacity: 0.9; + } + 100% { + transform: scale(2.6); + opacity: 0; + } +} +@keyframes connector-sweep { + 0% { + clip-path: inset(0 100% 0 0); + } + 100% { + clip-path: inset(0 0 0 0); + } +} +@keyframes label-in { + 0% { + opacity: 0.35; + } + 100% { + opacity: 1; + } +} +@keyframes card-enter { + 0% { + opacity: 0; + transform: translateY(-8px) scale(0.985); + } + 100% { + opacity: 1; + transform: none; + } +} +@keyframes odo-up { + from { + transform: translateY(0); + } + to { + transform: translateY(-1em); + } +} +@keyframes odo-down { + from { + transform: translateY(-1em); + } + to { + transform: translateY(0); + } +} +@media (prefers-reduced-motion: reduce) { + .node.live .bead, + .node.just-lit .bead::after, + .node.just-lit::before, + .node.just-lit .node-label, + .node.just-lit .node-time, + .mail.card-enter, + .metric strong .odo { + animation: none; + } +} + +.mail-err { + margin-top: 12px; + padding: 8px 10px; + border: 1px solid #4a2626; + border-radius: var(--radius-sm); + background: #1a0f0f; + color: var(--color-orange); + font-family: var(--font-ibm); + font-size: 11px; + line-height: 1.4; +} + +.empty { + border: 1px dashed var(--color-shade4); + border-radius: var(--radius); + padding: 34px 18px; + color: var(--color-n4); + text-align: center; + font-size: 13px; + line-height: 1.5; +} + +.page-foot { + min-height: 58px; + display: flex; + align-items: center; + justify-content: center; + gap: 11px; + border-top: 1px solid var(--color-shade4); +} +.page-foot .by { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + font-weight: 600; + letter-spacing: 0.12em; + text-transform: uppercase; +} +.page-foot img { + height: 26px; + width: auto; + opacity: 0.85; +} + +@media (max-width: 1040px) { + /* Stack the panels at their natural heights and use page-level scrolling. */ + .shell { + height: auto; + min-height: 100vh; + } + .workspace { + grid-template-columns: 1fr; + grid-template-rows: none; + align-items: start; + } + .console { + min-height: 560px; + } +} +@media (max-width: 560px) { + .metrics { + grid-template-columns: repeat(2, 1fr); + } + .node-label { + font-size: 9px; + } +} diff --git a/spacetime-resend-ts/example/scripts/test-message.ts b/spacetime-resend-ts/example/scripts/test-message.ts new file mode 100644 index 00000000000..c7d2169c2c0 --- /dev/null +++ b/spacetime-resend-ts/example/scripts/test-message.ts @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import { messageHtml } from '../spacetimedb/src/message'; + +const html = messageHtml( + 'Hello & friends\nNext line\n\nSecond paragraph' +); + +assert.match(html, /BlinkMacSystemFont/); +assert.match(html, /max-width:560px/); +assert.match(html, /Hello <team> & friends
Next line/); +assert.match(html, /Second paragraph/); +assert.equal((html.match(/

/); + +console.log('resend message tests passed'); diff --git a/spacetime-resend-ts/example/server.ts b/spacetime-resend-ts/example/server.ts new file mode 100644 index 00000000000..5232d87182a --- /dev/null +++ b/spacetime-resend-ts/example/server.ts @@ -0,0 +1,237 @@ +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 { + discardStoredServerToken, + exampleUiAssetsDir, + grantServerIdentity, + loadServerToken, + saveServerToken, +} from '@spacetimedb/example-ui/server'; +import { DbConnection, type ErrorContext } from './src/module_bindings'; + +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 secrets/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 ?? '8790', 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 STDB_HTTP = process.env.STDB_HTTP ?? 'http://127.0.0.1:3000'; +const DB_NAME = process.env.SPACETIMEDB_DB_NAME ?? 'spacetime-resend-example'; +const SPACETIME_BIN = process.env.SPACETIME_BIN?.trim() || 'spacetime'; +const RESEND_API_KEY = process.env.RESEND_API_KEY ?? ''; +const RESEND_WEBHOOK_SECRET = process.env.RESEND_WEBHOOK_SECRET ?? ''; +const DEFAULT_FROM = process.env.DEFAULT_FROM ?? 'onboarding@resend.dev'; +const RESEND_TEST_RECIPIENTS = [ + 'delivered@resend.dev', + 'bounced@resend.dev', + 'complained@resend.dev', +]; +const ALLOWED_RECIPIENTS = [ + ...new Set([ + ...RESEND_TEST_RECIPIENTS, + ...(process.env.RESEND_ALLOWED_RECIPIENTS ?? '') + .split(',') + .map(value => value.trim().toLowerCase()) + .filter(Boolean), + ]), +]; +const SERVER_TOKEN_PATH = path.resolve(__dirname, '.stdb-server-token'); + +let stdb: DbConnection | null = null; +let resendConfigured = false; + +type ConnectedServer = { + connection: DbConnection; + identity: string; +}; + +function connectAttempt(token: string | undefined): Promise { + return new Promise((resolve, reject) => { + let builder = DbConnection.builder() + .withUri(STDB_URI) + .withDatabaseName(DB_NAME) + .onConnect((connection, identity, nextToken) => { + if (!process.env.STDB_SERVER_TOKEN?.trim()) { + saveServerToken(SERVER_TOKEN_PATH, nextToken); + } + resolve({ connection, identity: identity.toHexString() }); + }) + .onDisconnect((_ctx, err) => { + console.error( + `[stdb] disconnected: ${err?.message ?? 'unknown'} - exiting for supervisor restart` + ); + process.exit(1); + }) + .onConnectError((_ctx: ErrorContext, err) => reject(err)); + if (token) builder = builder.withToken(token); + builder.build(); + }); +} + +async function connect(): Promise { + const stored = loadServerToken( + SERVER_TOKEN_PATH, + process.env.STDB_SERVER_TOKEN + ); + try { + return await connectAttempt(stored.token); + } catch (error) { + if (stored.source !== 'file') throw error; + discardStoredServerToken(SERVER_TOKEN_PATH); + console.warn( + '[stdb] stored server token was rejected; creating a new identity' + ); + return connectAttempt(undefined); + } +} + +function requireStdb(): DbConnection { + if (!stdb) throw new Error('STDB not connected yet'); + return stdb; +} + +const app = express(); + +// Webhook uses the raw body because Svix signs raw bytes. Register it before express.json(). +app.post( + '/webhook/resend', + express.raw({ type: '*/*', limit: '512kb' }), + handleResendWebhook +); + +app.use(express.json({ limit: '512kb' })); +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, + resendConfigured, + defaultFrom: DEFAULT_FROM, + allowedRecipients: ALLOWED_RECIPIENTS, + }); +}); + +async function handleResendWebhook(req: Request, res: Response): Promise { + const rawBody = + req.body instanceof Buffer ? req.body : Buffer.from(String(req.body ?? '')); + const url = `${STDB_HTTP}/v1/database/${DB_NAME}/route/webhook/resend`; + + const headers: Record = { + 'content-type': 'application/json', + }; + for (const name of ['svix-id', 'svix-timestamp', 'svix-signature']) { + const value = req.headers[name]; + if (typeof value === 'string') headers[name] = value; + else if (Array.isArray(value)) headers[name] = value.join(','); + } + + try { + const upstream = await fetch(url, { + method: 'POST', + headers, + body: rawBody, + }); + const text = await upstream.text(); + res.status(upstream.status).send(text); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + console.error(`[webhook] passthrough to STDB route failed: ${reason}`); + res.status(502).send(`passthrough failed: ${reason}`); + } +} + +async function bootstrapResendConfig(): Promise { + if (!RESEND_API_KEY) { + resendConfigured = false; + process.stdout.write( + ' ! RESEND_API_KEY missing: Dispatch connects; email sends require configuration\n' + ); + return; + } + + await requireStdb().procedures['resend.setResendConfig']({ + apiKey: RESEND_API_KEY, + webhookSigningSecret: RESEND_WEBHOOK_SECRET || undefined, + defaultFrom: DEFAULT_FROM, + }); + await requireStdb().procedures.setDispatchPolicy({ + allowedRecipientsJson: JSON.stringify(ALLOWED_RECIPIENTS), + }); + resendConfigured = true; + process.stdout.write(' + Resend config loaded from server environment\n'); +} + +(async () => { + console.log(`[stdb] connecting to ${STDB_URI}/${DB_NAME} ...`); + try { + const connected = await connect(); + stdb = connected.connection; + grantServerIdentity({ + spacetimeBin: SPACETIME_BIN, + server: STDB_HTTP, + database: DB_NAME, + procedure: 'resend.add_admin_identity', + identity: connected.identity, + }); + console.log(`[stdb] connected as authorized server ${connected.identity}`); + } catch (err) { + console.error( + `[stdb] connection or authorization failed: ${err instanceof Error ? err.message : String(err)}` + ); + console.error( + '[stdb] is the SpacetimeDB host running and the module published?' + ); + process.exit(1); + } + + try { + await bootstrapResendConfig(); + } catch (err) { + console.error( + `[resend] configuration failed: ${err instanceof Error ? err.message : String(err)}` + ); + process.exit(1); + } + + app.listen(PORT, HOST, () => { + process.stdout.write(`\nDispatch running at http://${HOST}:${PORT}\n`); + if (!RESEND_WEBHOOK_SECRET) { + process.stdout.write( + ' ! RESEND_WEBHOOK_SECRET not set - incoming webhooks are rejected\n' + ); + } + process.stdout.write( + ` webhook endpoint: POST http://127.0.0.1:${PORT}/webhook/resend\n` + ); + process.stdout.write(` database: ${STDB_URI}/${DB_NAME}\n\n`); + }); +})(); diff --git a/spacetime-resend-ts/example/spacetimedb/.npmrc b/spacetime-resend-ts/example/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-resend-ts/example/spacetimedb/package.json b/spacetime-resend-ts/example/spacetimedb/package.json new file mode 100644 index 00000000000..375d324832a --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/package.json @@ -0,0 +1,20 @@ +{ + "name": "spacetime-resend-example-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-resend-example", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-resend-example" + }, + "dependencies": { + "@spacetimedb/rate-limit": "workspace:*", + "@spacetimedb/resend": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-resend-ts/example/spacetimedb/src/index.ts b/spacetime-resend-ts/example/spacetimedb/src/index.ts new file mode 100644 index 00000000000..fccdac9112a --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/src/index.ts @@ -0,0 +1,273 @@ +// The browser never talks to Resend directly and is never granted admin. It calls +// host procedures that forward to the submodule through `ctx.as.resend`. Resend's +// base tables stay private; caller-scoped views below expose only the current +// connection's dispatches. + +import { schema, table, t, SenderError, Router } from 'spacetimedb/server'; +import * as resend from '@spacetimedb/resend/submodule'; +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; +import { messageHtml } from './message'; + +const dispatchPolicy = table( + { name: 'dispatch_policy', public: false }, + { + singleton: t.bool().primaryKey(), + allowedRecipientsJson: t.string(), + updatedAt: t.timestamp(), + } +); + +// Removed dispatches stay in the Resend tables so later webhooks update the +// existing row instead of recreating it. The views skip these ids. +const removedDispatch = table( + { name: 'removed_dispatch', public: false }, + { resendId: t.string().primaryKey() } +); + +const spacetimedb = schema({ + resend, + rateLimit, + dispatchPolicy, + removedDispatch, +}); + +function subjectFor(ctx: { sender: { toHexString(): string } }): string { + return ctx.sender.toHexString(); +} + +export const myDispatchEmails = spacetimedb.view( + { name: 'my_dispatch_emails', public: true }, + resend.t.array(resend.resendEmailTable.rowType), + ctx => + [...ctx.db.resend.resendEmail.byUserId.filter(subjectFor(ctx))].filter( + email => !ctx.db.removedDispatch.resendId.find(email.resendId) + ) +); + +export const myDispatchDeliveryEvents = spacetimedb.view( + { name: 'my_dispatch_delivery_events', public: true }, + resend.t.array(resend.resendDeliveryEventTable.rowType), + ctx => { + const out = []; + for (const email of ctx.db.resend.resendEmail.byUserId.filter( + subjectFor(ctx) + )) { + if (ctx.db.removedDispatch.resendId.find(email.resendId)) continue; + for (const event of ctx.db.resend.resendDeliveryEvent.byResendId.filter( + email.resendId + )) { + out.push(event); + } + } + return out; + } +); + +const MAX_SUBJECT = 200; +const MAX_MESSAGE = 5000; +const MAX_ALLOWED_RECIPIENTS = 10; +const MAX_RECIPIENT_POLICY_LENGTH = 4096; +const CALLER_SEND_LIMIT = 5; +const CALLER_WINDOW_SECONDS = 10 * 60; +const GLOBAL_SEND_LIMIT = 25; +const GLOBAL_WINDOW_SECONDS = 60 * 60; +const callerLimiter = rateLimit.client({ + scope: 'dispatch.send.caller', + limit: CALLER_SEND_LIMIT, + windowSeconds: CALLER_WINDOW_SECONDS, +}); +const globalLimiter = rateLimit.client({ + scope: 'dispatch.send.global', + limit: GLOBAL_SEND_LIMIT, + windowSeconds: GLOBAL_WINDOW_SECONDS, +}); + +function fail(message: string): never { + throw new SenderError(`dispatch.${message}`); +} + +function normalizeEmail(email: string): string { + const out = email.trim().toLowerCase(); + if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(out)) fail('invalid_email'); + return out; +} + +function parseAllowedRecipients(value: string): string[] { + if (value.length > MAX_RECIPIENT_POLICY_LENGTH) { + fail('recipient_policy_too_large'); + } + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + fail('invalid_recipient_policy'); + } + if (!Array.isArray(parsed) || parsed.length === 0) { + fail('invalid_recipient_policy'); + } + const recipients = [ + ...new Set(parsed.map(value => normalizeEmail(String(value)))), + ]; + if (recipients.length > MAX_ALLOWED_RECIPIENTS) { + fail('too_many_allowed_recipients'); + } + return recipients; +} + +function clean( + value: string | undefined, + fallback: string, + max: number +): string { + const out = (value ?? '').trim().replace(/\s+/g, ' '); + return (out || fallback).slice(0, max); +} + +const dispatchSendResult = t.object('DispatchSendResult', { + ok: t.bool(), + resendId: t.option(t.string()), + message: t.string(), +}); + +export const setDispatchPolicy = spacetimedb.procedure( + { allowedRecipientsJson: t.string() }, + t.bool(), + (ctx, args) => { + const isAdmin = ctx.withTx( + tx => tx.db.resend.resendAdminIdentity.identity.find(ctx.sender) != null + ); + if (!isAdmin) fail('not_authorized'); + const recipients = parseAllowedRecipients(args.allowedRecipientsJson); + ctx.withTx(tx => { + const existing = tx.db.dispatchPolicy.singleton.find(true); + const row = { + singleton: true, + allowedRecipientsJson: JSON.stringify(recipients), + updatedAt: ctx.timestamp, + }; + if (existing) tx.db.dispatchPolicy.singleton.update(row); + else tx.db.dispatchPolicy.insert(row); + }); + return true; + } +); + +// The host policy restricts recipients and applies caller and global quotas before +// delegating delivery through the private Resend configuration. +export const sendDispatch = spacetimedb.procedure( + { + to: t.string(), + subject: t.string(), + message: t.string(), + }, + dispatchSendResult, + (ctx, args) => { + const to = normalizeEmail(args.to); + const subject = clean(args.subject, '(no subject)', MAX_SUBJECT); + const message = (args.message ?? '').trim().slice(0, MAX_MESSAGE); + if (!message) fail('empty_message'); + + const policyJson = ctx.withTx( + tx => + tx.db.dispatchPolicy.singleton.find(true)?.allowedRecipientsJson ?? null + ); + if (policyJson == null) fail('policy_missing'); + const allowed = parseAllowedRecipients(policyJson); + if (!allowed.includes(to)) fail('recipient_not_allowed'); + + const authorization = ctx.withTx(tx => { + const caller = callerLimiter.consume(tx.as.rateLimit, { + key: subjectFor(ctx), + }); + if (!caller.allowed) return 'rate_limited' as const; + const global = globalLimiter.consume(tx.as.rateLimit, { key: 'global' }); + return global.allowed ? ('allowed' as const) : ('rate_limited' as const); + }); + if (authorization !== 'allowed') fail(authorization); + + try { + const result = resend.sendEmailRequest(ctx.as.resend, { + to: [to], + subject, + html: messageHtml(message), + text: message, + tagsJson: JSON.stringify([ + { name: 'source', value: 'dispatch' }, + { name: 'userId', value: subjectFor(ctx) }, + ]), + }); + return { + ok: true, + resendId: result.resendId, + message: `Dispatched to ${to}.`, + }; + } catch { + return { + ok: false, + resendId: undefined, + message: 'dispatch.delivery_failed', + }; + } + } +); + +const dispatchDeleteResult = t.object('DispatchDeleteResult', { + ok: t.bool(), + removed: t.u32(), +}); + +// Remove dispatches from the caller's log. This is a demo convenience so the +// log can be pruned. +export const deleteDispatch = spacetimedb.procedure( + { resendId: t.string() }, + dispatchDeleteResult, + (ctx, args) => { + return ctx.withTx(tx => { + const row = tx.db.resend.resendEmail.resendId.find(args.resendId); + if ( + row?.userId !== subjectFor(ctx) || + tx.db.removedDispatch.resendId.find(args.resendId) + ) { + return { ok: true, removed: 0 }; + } + tx.db.removedDispatch.insert({ resendId: args.resendId }); + return { ok: true, removed: 1 }; + }); + } +); + +export const clearDispatches = spacetimedb.procedure( + {}, + dispatchDeleteResult, + ctx => { + return ctx.withTx(tx => { + let removed = 0; + for (const row of tx.db.resend.resendEmail.byUserId.filter( + subjectFor(ctx) + )) { + if (tx.db.removedDispatch.resendId.find(row.resendId)) continue; + tx.db.removedDispatch.insert({ resendId: row.resendId }); + removed += 1; + } + return { ok: true, removed }; + }); + } +); + +// Resend posts delivery webhooks straight to the database over a native STDB HTTP +// route. The submodule verifies the svix signature in-module (via crypto-ts) and +// ingests. No Node relay does any of this work. +const resendWebhookHandler = resend.makeResendWebhookHandler(); +export const resendWebhook = spacetimedb.httpHandler((ctx, req) => + resendWebhookHandler(ctx.as.resend, req) +); +export const router = spacetimedb.httpRouter( + new Router().post('/webhook/resend', resendWebhook) +); + +export const init = spacetimedb.init(ctx => { + resend.install(ctx.as.resend); + rateLimit.install(ctx.as.rateLimit); +}); + +export default spacetimedb; diff --git a/spacetime-resend-ts/example/spacetimedb/src/message.ts b/spacetime-resend-ts/example/spacetimedb/src/message.ts new file mode 100644 index 00000000000..38656a3766c --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/src/message.ts @@ -0,0 +1,20 @@ +function escapeHtml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>'); +} + +export function messageHtml(message: string): string { + const paragraphs = message + .split(/\n{2,}/) + .map(block => escapeHtml(block).replace(/\n/g, '
')) + .map(block => `

${block}

`) + .join(''); + return [ + "
', + paragraphs, + '
', + ].join(''); +} diff --git a/spacetime-resend-ts/example/spacetimedb/tsconfig.json b/spacetime-resend-ts/example/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..f004a6cbc79 --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/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"], + "exclude": ["node_modules"] +} diff --git a/spacetime-resend-ts/example/src/app.ts b/spacetime-resend-ts/example/src/app.ts new file mode 100644 index 00000000000..1193f9e73f4 --- /dev/null +++ b/spacetime-resend-ts/example/src/app.ts @@ -0,0 +1,673 @@ +import { + DbConnection, + tables, + type ErrorContext, + type EventContext, + type SubscriptionEventContext, +} from './module_bindings'; +import type { Timestamp } from 'spacetimedb'; +import { messageHtml } from '../spacetimedb/src/message'; + +type TableAccessor = { + 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; +}; + +// Mirrors the caller-scoped my_dispatch_emails view. Options arrive as +// `T | undefined`; status is a tagged enum. +type ResendEmail = { + resendId: string; + fromAddress: string; + toAddressesJson: string; + subject?: string; + status: { tag: string } | string; + lastError?: string; + bouncedAt?: Timestamp; + failedAt?: Timestamp; + failureReason?: string; + complained: boolean; + complainedAt?: Timestamp; + opened: boolean; + openedAt?: Timestamp; + clicked: boolean; + clickedAt?: Timestamp; + deliveredAt?: Timestamp; + sentAt?: Timestamp; + createdAt: Timestamp; + updatedAt: Timestamp; +}; + +type SendResult = { + ok: boolean; + resendId?: string; + message: string; +}; + +type ServerConfig = { + spacetimeUri: string; + databaseName: string; + resendConfigured: boolean; + defaultFrom: string; + allowedRecipients: string[]; +}; + +const $ = (id: string) => + document.getElementById(id) as T; + +let conn: DbConnection | null = null; +let currentConfig: ServerConfig | null = null; +let sending = false; + +function escapeHtml(value: unknown): string { + return String(value ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function tagOf(value: { tag: string } | string | undefined): string { + if (value && typeof value === 'object' && 'tag' in value) return value.tag; + return String(value ?? ''); +} + +function timestampMs(ts: Timestamp | undefined): number { + if (!ts) return 0; + return Number(ts.microsSinceUnixEpoch / 1000n); +} + +function timeLabel(ts: Timestamp | undefined): string { + const ms = timestampMs(ts); + if (!ms) return ''; + return new Date(ms).toLocaleTimeString([], { + hour: 'numeric', + minute: '2-digit', + second: '2-digit', + }); +} + +const AVATAR_COLORS = [ + '#4cf490', + '#02befa', + '#a880ff', + '#fbdc8e', + '#ff9e9e', + '#00ccb4', + '#ff80fb', +]; + +// The Resend test addresses always get the same, recognizable colour. +const KNOWN_AVATAR_COLORS: Record = { + 'delivered@resend.dev': '#4cf490', // green + 'bounced@resend.dev': '#ff9e9e', // orange + 'complained@resend.dev': '#a880ff', // purple +}; + +function avatarColor(seed: string): string { + const known = KNOWN_AVATAR_COLORS[seed.toLowerCase()]; + if (known) return known; + let h = 0; + for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0; + return AVATAR_COLORS[h % AVATAR_COLORS.length]; +} + +function recipient(row: ResendEmail): string { + try { + const parsed = JSON.parse(row.toAddressesJson); + if (Array.isArray(parsed) && parsed.length > 0) return String(parsed[0]); + } catch { + /* fall through */ + } + return row.toAddressesJson; +} + +function initials(email: string): string { + const local = email.split('@')[0] ?? email; + return (local.slice(0, 2) || '?').toUpperCase(); +} + +function showError(message: string) { + $('form-error').textContent = message; +} + +function clearError() { + $('form-error').textContent = ''; +} + +let flashTimer: ReturnType | undefined; + +function flashSent() { + const btn = $('send-btn') as HTMLButtonElement; + btn.classList.add('sent'); + btn.textContent = 'Sent'; + if (flashTimer) clearTimeout(flashTimer); + flashTimer = setTimeout(() => { + btn.classList.remove('sent'); + if (!sending) btn.textContent = 'Send'; + }, 1800); +} + +async function loadServerConfig(): Promise { + const res = await fetch('/api/config'); + if (!res.ok) throw new Error(`/api/config returned ${res.status}`); + return (await res.json()) as ServerConfig; +} + +async function connect(config: ServerConfig): Promise { + return new Promise((resolve, reject) => { + DbConnection.builder() + .withUri(config.spacetimeUri) + .withDatabaseName(config.databaseName) + .onConnect(c => resolve(c)) + .onDisconnect((_ctx, err) => { + showError(`Disconnected: ${err?.message ?? 'connection lost'}`); + }) + .onConnectError((_ctx: ErrorContext, err) => reject(err)) + .build(); + }); +} + +function getTableAccessor(name: string): TableAccessor | undefined { + const db = (conn?.db ?? {}) as Record | undefined>; + return db[name]; +} + +function emails(): ResendEmail[] { + return [ + ...(getTableAccessor('myDispatchEmails')?.iter() ?? []), + ].sort((a, b) => { + return timestampMs(b.createdAt) - timestampMs(a.createdAt); + }); +} + +type Node = { + key: string; + label: string; + at?: Timestamp; + state: 'done' | 'live' | 'pending' | 'bad' | 'warn'; +}; + +// Turn a stored email into an ordered set of lifecycle nodes. The EmailStatus enum +// tops out at Delivered; Opened/Clicked are booleans; negatives are terminal. +function timeline(row: ResendEmail): Node[] { + const status = tagOf(row.status); + const nodes: Node[] = [ + { key: 'queued', label: 'Queued', at: row.createdAt, state: 'done' }, + ]; + + const sentReached = + Boolean(row.sentAt) || + Boolean(row.deliveredAt) || + row.opened || + row.clicked || + status === 'Sent' || + status === 'Delivered'; + nodes.push({ + key: 'sent', + label: 'Sent', + at: row.sentAt, + state: sentReached ? 'done' : 'pending', + }); + + if (status === 'Bounced') { + nodes.push({ + key: 'bounced', + label: 'Bounced', + at: row.bouncedAt, + state: 'bad', + }); + return nodes; + } + if (status === 'Failed') { + nodes.push({ + key: 'failed', + label: 'Failed', + at: row.failedAt, + state: 'bad', + }); + return nodes; + } + if (status === 'Cancelled') { + nodes.push({ key: 'cancelled', label: 'Cancelled', state: 'warn' }); + return nodes; + } + + // A complaint (marked as spam) implies the mail was delivered, and it is terminal. + const deliveredReached = + Boolean(row.deliveredAt) || + row.opened || + row.clicked || + status === 'Delivered' || + row.complained; + const delayed = status === 'DeliveryDelayed' && !deliveredReached; + nodes.push({ + key: 'delivered', + label: delayed ? 'Delayed' : 'Delivered', + at: row.deliveredAt, + state: deliveredReached ? 'done' : delayed ? 'warn' : 'pending', + }); + + if (row.complained) { + // Terminal: show completed positive steps followed by Complaint. + // No trailing "pending" steps and no live pulse - the lifecycle is over. + if (row.opened) + nodes.push({ + key: 'opened', + label: 'Opened', + at: row.openedAt, + state: 'done', + }); + if (row.clicked) + nodes.push({ + key: 'clicked', + label: 'Clicked', + at: row.clickedAt, + state: 'done', + }); + nodes.push({ + key: 'complaint', + label: 'Complaint', + at: row.complainedAt, + state: 'bad', + }); + return nodes; + } + + nodes.push({ + key: 'opened', + label: 'Opened', + at: row.openedAt, + state: row.opened ? 'done' : 'pending', + }); + nodes.push({ + key: 'clicked', + label: 'Clicked', + at: row.clickedAt, + state: row.clicked ? 'done' : 'pending', + }); + + // The furthest reached positive node is the live frontier. A completed later + // node makes the final completed positive node the subtle accent. + const lastDone = nodes.map(n => n.state === 'done').lastIndexOf(true); + if ( + lastDone > 0 && + nodes[lastDone].state === 'done' && + nodes.some(n => n.state === 'pending') + ) { + nodes[lastDone].state = 'live'; + } + return nodes; +} + +function headPill(row: ResendEmail): { cls: string; text: string } { + const status = tagOf(row.status); + if (status === 'Bounced') return { cls: 'red', text: 'Bounced' }; + if (status === 'Failed') return { cls: 'red', text: 'Failed' }; + if (status === 'Cancelled') return { cls: 'muted', text: 'Cancelled' }; + if (row.complained) return { cls: 'red', text: 'Complaint' }; + if (row.clicked) return { cls: 'green', text: 'Clicked' }; + if (row.opened) return { cls: 'green', text: 'Opened' }; + if (row.deliveredAt || status === 'Delivered') + return { cls: 'green', text: 'Delivered' }; + if (status === 'DeliveryDelayed') return { cls: 'yellow', text: 'Delayed' }; + if (row.sentAt || status === 'Sent') return { cls: 'green', text: 'Sent' }; + return { cls: 'muted', text: 'Queued' }; +} + +// Per-email rendered-node keys ensure each changed transition animates once. +const lastReached = new Map>(); +const knownEmails = new Set(); +const lastCounts: Record = { + sent: -1, + delivered: -1, + opened: -1, + bounced: -1, +}; + +function prefersReducedMotion(): boolean { + return ( + typeof matchMedia === 'function' && + matchMedia('(prefers-reduced-motion: reduce)').matches + ); +} + +// Odometer roll: stack the current and incoming values in a clip window. An +// increase rolls up from below; a decrease rolls down. +function rollNumber(el: HTMLElement, from: number, to: number) { + const up = to > from; + const top = up ? from : to; + const bottom = up ? to : from; + el.innerHTML = + `` + + `${top}${bottom}` + + ``; + const odo = el.querySelector('.odo'); + if (!odo) { + el.textContent = String(to); + return; + } + // Collapse back to a plain number once the roll finishes (or is superseded). + const settle = () => { + if (el.contains(odo)) el.textContent = String(to); + }; + odo.addEventListener('animationend', settle, { once: true }); + setTimeout(settle, 600); +} + +function bumpMetric(id: string, key: string, value: number) { + const el = $(id); + const prev = lastCounts[key]; + lastCounts[key] = value; + if (prev < 0 || prev === value || prefersReducedMotion()) { + el.textContent = String(value); + return; + } + rollNumber(el, prev, value); +} + +function renderMetrics(list: ResendEmail[]) { + const delivered = list.filter( + r => + r.deliveredAt || r.opened || r.clicked || tagOf(r.status) === 'Delivered' + ).length; + const opened = list.filter(r => r.opened).length; + const bounced = list.filter(r => { + const s = tagOf(r.status); + return s === 'Bounced' || s === 'Failed' || r.complained; + }).length; + bumpMetric('count-sent', 'sent', list.length); + bumpMetric('count-delivered', 'delivered', delivered); + bumpMetric('count-opened', 'opened', opened); + bumpMetric('count-bounced', 'bounced', bounced); +} + +function nodeHtml(node: Node, lit: boolean): string { + const time = node.at ? timeLabel(node.at) : ''; + return ` +
+ + ${escapeHtml(node.label)} + ${escapeHtml(time)} +
`; +} + +function mailHtml( + row: ResendEmail, + nodes: Node[], + newlyLit: Set, + isNew: boolean +): string { + const to = recipient(row); + const pill = headPill(row); + const bad = pill.cls === 'red'; + const subject = + row.subject && row.subject.length ? row.subject : '(no subject)'; + const track = nodes.map(n => nodeHtml(n, newlyLit.has(n.key))).join(''); + const error = + bad && row.failureReason + ? `
${escapeHtml(row.failureReason)}
` + : bad && row.lastError + ? `
${escapeHtml(row.lastError)}
` + : ''; + return ` +
+
+ ${escapeHtml(initials(to))} + + ${escapeHtml(to)} + ${escapeHtml(subject)} + + ${escapeHtml(timeLabel(row.createdAt))} + +
+
${track}
+ ${error} +
`; +} + +function reachedKeys(nodes: Node[]): Set { + return new Set(nodes.filter(n => n.state !== 'pending').map(n => n.key)); +} + +function render() { + const list = emails(); + renderMetrics(list); + $('feed-count').textContent = `${list.length} sent`; + ($('clear-btn') as HTMLButtonElement).disabled = list.length === 0; + + if (list.length === 0) { + $('feed').innerHTML = + `
No dispatches yet.
Compose a message and hit Send to watch it move.
`; + lastReached.clear(); + knownEmails.clear(); + return; + } + + const entries = list.map(row => ({ row, nodes: timeline(row) })); + + $('feed').innerHTML = entries + .map(({ row, nodes }) => { + const reached = reachedKeys(nodes); + const prev = lastReached.get(row.resendId); + const isNew = !knownEmails.has(row.resendId); + const newlyLit = new Set(); + if (prev) for (const k of reached) if (!prev.has(k)) newlyLit.add(k); + return mailHtml(row, nodes, newlyLit, isNew); + }) + .join(''); + + // Record post-render state so the next render can diff against it. + const currentIds = new Set(); + for (const { row, nodes } of entries) { + lastReached.set(row.resendId, reachedKeys(nodes)); + knownEmails.add(row.resendId); + currentIds.add(row.resendId); + } + for (const id of [...knownEmails]) { + if (!currentIds.has(id)) { + knownEmails.delete(id); + lastReached.delete(id); + } + } +} + +// Coalesce the burst of table events from a single webhook (email row update + +// delivery-event insert land together) into one render, so the change diff sees the +// whole transition at once and animates the node that advanced. +let renderScheduled = false; +function scheduleRender() { + if (renderScheduled) return; + renderScheduled = true; + setTimeout(() => { + renderScheduled = false; + render(); + }, 0); +} + +function registerCallbacksForTable(name: string): void { + const accessor = getTableAccessor(name); + if (!accessor) throw new Error(`missing table accessor: ${name}`); + accessor.onInsert(() => scheduleRender()); + accessor.onUpdate(() => scheduleRender()); + accessor.onDelete(() => scheduleRender()); +} + +function registerRowCallbacks(): void { + for (const name of ['myDispatchEmails', 'myDispatchDeliveryEvents']) { + registerCallbacksForTable(name); + } +} + +function subscribeToTables(connection: DbConnection): void { + connection + .subscriptionBuilder() + .onApplied((_ctx: SubscriptionEventContext) => { + render(); + if (!currentConfig?.resendConfigured) { + showError( + 'RESEND_API_KEY is missing in this example server environment.' + ); + } + }) + .onError((ctx: ErrorContext) => { + console.error('subscription error:', ctx.event); + showError('Subscription failed. Check the server console.'); + }) + .subscribe([tables.myDispatchEmails, tables.myDispatchDeliveryEvents]); +} + +async function sendDispatch( + to: string, + subject: string, + message: string +): Promise { + if (!conn) throw new Error('not connected'); + return conn.procedures.sendDispatch({ to, subject, message }); +} + +async function deleteDispatch(resendId: string): Promise { + if (!conn) throw new Error('not connected'); + await conn.procedures.deleteDispatch({ resendId }); +} + +async function clearDispatches(): Promise { + if (!conn) throw new Error('not connected'); + await conn.procedures.clearDispatches({}); +} + +function setSending(next: boolean) { + sending = next; + const btn = $('send-btn') as HTMLButtonElement; + btn.disabled = next; + if (next) btn.textContent = 'Sending...'; + else if (!btn.classList.contains('sent')) btn.textContent = 'Send'; +} + +function renderPreview() { + const subject = + ($('subject-input') as HTMLInputElement).value.trim() || '(no subject)'; + const message = ($('message-input') as HTMLTextAreaElement).value.trim(); + const from = currentConfig?.defaultFrom || 'onboarding@resend.dev'; + const body = message + ? messageHtml(message) + : 'Nothing to preview yet.'; + $('message-preview').innerHTML = ` +
+
${escapeHtml(subject)}
+
From ${escapeHtml(from)}
+
+
${body}
`; +} + +function setMsgTab(tab: 'write' | 'preview') { + const isPreview = tab === 'preview'; + if (isPreview) renderPreview(); + ($('message-input') as HTMLTextAreaElement).hidden = isPreview; + $('message-preview').hidden = !isPreview; + document.querySelectorAll('.msg-tab').forEach(b => { + b.classList.toggle('active', b.dataset.tab === tab); + }); +} + +async function submitCompose() { + if (sending) return; + const to = ($('to-input') as HTMLInputElement).value.trim(); + const subject = ($('subject-input') as HTMLInputElement).value.trim(); + const message = ($('message-input') as HTMLTextAreaElement).value.trim(); + if (!to) { + showError('Add a recipient first.'); + return; + } + if (!message) { + showError('Write a message before sending.'); + return; + } + clearError(); + setSending(true); + try { + const result = await sendDispatch(to, subject, message); + setSending(false); + if (result.ok) { + ($('subject-input') as HTMLInputElement).value = ''; + ($('message-input') as HTMLTextAreaElement).value = ''; + setMsgTab('write'); + flashSent(); + } else { + showError(result.message); + } + } catch (err) { + setSending(false); + showError(err instanceof Error ? err.message : String(err)); + } +} + +function registerUiHandlers(): void { + $('compose-form').addEventListener('submit', event => { + event.preventDefault(); + submitCompose().catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); + }); + }); + + document.querySelectorAll('.msg-tab').forEach(button => { + button.addEventListener('click', () => { + setMsgTab(button.dataset.tab === 'preview' ? 'preview' : 'write'); + }); + }); + + document + .querySelectorAll('[data-fill]') + .forEach(button => { + button.addEventListener('click', () => { + const email = button.dataset.fill ?? 'delivered@resend.dev'; + ($('to-input') as HTMLInputElement).value = email; + const subject = $('subject-input') as HTMLInputElement; + const message = $('message-input') as HTMLTextAreaElement; + if (!subject.value.trim()) subject.value = 'Hello from Dispatch'; + if (!message.value.trim()) + message.value = 'Watching this one travel through the pipeline.'; + clearError(); + ($('to-input') as HTMLInputElement).focus(); + }); + }); + + $('feed').addEventListener('click', event => { + const btn = (event.target as HTMLElement).closest( + '[data-del]' + ); + if (!btn) return; + const resendId = btn.dataset.del; + if (!resendId) return; + btn.setAttribute('disabled', 'true'); + deleteDispatch(resendId).catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); + }); + }); + + $('clear-btn').addEventListener('click', () => { + clearDispatches().catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); + }); + }); +} + +async function main() { + registerUiHandlers(); + currentConfig = await loadServerConfig(); + const recipientInput = $('to-input') as HTMLInputElement; + recipientInput.value = currentConfig.allowedRecipients[0] ?? ''; + conn = await connect(currentConfig); + registerRowCallbacks(); + subscribeToTables(conn); +} + +main().catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/clear_dispatches_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/clear_dispatches_procedure.ts new file mode 100644 index 00000000000..6621a844b9c --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/clear_dispatches_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 { + DispatchDeleteResult, +} from "./types"; + +export const params = { +}; +export const returnType = DispatchDeleteResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/delete_dispatch_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/delete_dispatch_procedure.ts new file mode 100644 index 00000000000..9e246ad1174 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/delete_dispatch_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 { + DispatchDeleteResult, +} from "./types"; + +export const params = { + resendId: __t.string(), +}; +export const returnType = DispatchDeleteResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/index.ts b/spacetime-resend-ts/example/src/module_bindings/index.ts new file mode 100644 index 00000000000..4d2fadb97d6 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/index.ts @@ -0,0 +1,242 @@ +// 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.11.0 (commit dfdccc7e468cc3d378901eac5ee498b4243f4442). + +/* 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 all procedure arg schemas +import * as ClearDispatchesProcedure from "./clear_dispatches_procedure"; +import * as DeleteDispatchProcedure from "./delete_dispatch_procedure"; +import * as SendDispatchProcedure from "./send_dispatch_procedure"; +import * as SetDispatchPolicyProcedure from "./set_dispatch_policy_procedure"; + +// Import all table schema definitions +import MyDispatchDeliveryEventsRow from "./my_dispatch_delivery_events_table"; +import MyDispatchEmailsRow from "./my_dispatch_emails_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 Resend_IngestResendWebhookReducer from "./resend/ingest_resend_webhook_reducer"; +import Resend_ReplayWebhookEventReducer from "./resend/replay_webhook_event_reducer"; +import RateLimit_AddRateLimitAdminReducer from "./rateLimit/add_rate_limit_admin_reducer"; +import RateLimit_RemoveRateLimitAdminReducer from "./rateLimit/remove_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 Resend_AddAdminIdentityProcedure from "./resend/add_admin_identity_procedure"; +import * as Resend_CancelEmailProcedure from "./resend/cancel_email_procedure"; +import * as Resend_GetEmailProcedure from "./resend/get_email_procedure"; +import * as Resend_GetResendConfigStatusProcedure from "./resend/get_resend_config_status_procedure"; +import * as Resend_GetWebhookEventProcedure from "./resend/get_webhook_event_procedure"; +import * as Resend_ListDeliveryEventsForEmailProcedure from "./resend/list_delivery_events_for_email_procedure"; +import * as Resend_ListEmailsByOrgIdProcedure from "./resend/list_emails_by_org_id_procedure"; +import * as Resend_ListEmailsByStatusProcedure from "./resend/list_emails_by_status_procedure"; +import * as Resend_ListEmailsByUserIdProcedure from "./resend/list_emails_by_user_id_procedure"; +import * as Resend_RemoveAdminIdentityProcedure from "./resend/remove_admin_identity_procedure"; +import * as Resend_ResendApiRequestProcedure from "./resend/resend_api_request_procedure"; +import * as Resend_SendEmailProcedure from "./resend/send_email_procedure"; +import * as Resend_SetResendConfigProcedure from "./resend/set_resend_config_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({ + myDispatchDeliveryEvents: __table({ + name: 'my_dispatch_delivery_events', + indexes: [ + ], + constraints: [ + ], + }, MyDispatchDeliveryEventsRow), + myDispatchEmails: __table({ + name: 'my_dispatch_emails', + indexes: [ + ], + constraints: [ + ], + }, MyDispatchEmailsRow), + "rate_limit.rate_limit_config": __table({ + name: 'rate_limit.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), + "rate_limit.admin_rate_limit_buckets": __table({ + name: 'rate_limit.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("resend.ingest_resend_webhook", Resend_IngestResendWebhookReducer, "resend.ingestResendWebhook"), + __reducerSchema("resend.replay_webhook_event", Resend_ReplayWebhookEventReducer, "resend.replayWebhookEvent"), + __reducerSchema("rate_limit.add_rate_limit_admin", RateLimit_AddRateLimitAdminReducer, "rateLimit.addRateLimitAdmin"), + __reducerSchema("rate_limit.remove_rate_limit_admin", RateLimit_RemoveRateLimitAdminReducer, "rateLimit.removeRateLimitAdmin"), + __reducerSchema("rate_limit.reset_buckets", RateLimit_ResetBucketsReducer, "rateLimit.resetBuckets"), + __reducerSchema("rate_limit.update_config", RateLimit_UpdateConfigReducer, "rateLimit.updateConfig"), +); + +/** 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("clear_dispatches", ClearDispatchesProcedure.params, ClearDispatchesProcedure.returnType), + __procedureSchema("delete_dispatch", DeleteDispatchProcedure.params, DeleteDispatchProcedure.returnType), + __procedureSchema("send_dispatch", SendDispatchProcedure.params, SendDispatchProcedure.returnType), + __procedureSchema("set_dispatch_policy", SetDispatchPolicyProcedure.params, SetDispatchPolicyProcedure.returnType), + __procedureSchema("resend.add_admin_identity", Resend_AddAdminIdentityProcedure.params, Resend_AddAdminIdentityProcedure.returnType, "resend.addAdminIdentity"), + __procedureSchema("resend.cancel_email", Resend_CancelEmailProcedure.params, Resend_CancelEmailProcedure.returnType, "resend.cancelEmail"), + __procedureSchema("resend.get_email", Resend_GetEmailProcedure.params, Resend_GetEmailProcedure.returnType, "resend.getEmail"), + __procedureSchema("resend.get_resend_config_status", Resend_GetResendConfigStatusProcedure.params, Resend_GetResendConfigStatusProcedure.returnType, "resend.getResendConfigStatus"), + __procedureSchema("resend.get_webhook_event", Resend_GetWebhookEventProcedure.params, Resend_GetWebhookEventProcedure.returnType, "resend.getWebhookEvent"), + __procedureSchema("resend.list_delivery_events_for_email", Resend_ListDeliveryEventsForEmailProcedure.params, Resend_ListDeliveryEventsForEmailProcedure.returnType, "resend.listDeliveryEventsForEmail"), + __procedureSchema("resend.list_emails_by_org_id", Resend_ListEmailsByOrgIdProcedure.params, Resend_ListEmailsByOrgIdProcedure.returnType, "resend.listEmailsByOrgId"), + __procedureSchema("resend.list_emails_by_status", Resend_ListEmailsByStatusProcedure.params, Resend_ListEmailsByStatusProcedure.returnType, "resend.listEmailsByStatus"), + __procedureSchema("resend.list_emails_by_user_id", Resend_ListEmailsByUserIdProcedure.params, Resend_ListEmailsByUserIdProcedure.returnType, "resend.listEmailsByUserId"), + __procedureSchema("resend.remove_admin_identity", Resend_RemoveAdminIdentityProcedure.params, Resend_RemoveAdminIdentityProcedure.returnType, "resend.removeAdminIdentity"), + __procedureSchema("resend.resend_api_request", Resend_ResendApiRequestProcedure.params, Resend_ResendApiRequestProcedure.returnType, "resend.resendApiRequest"), + __procedureSchema("resend.send_email", Resend_SendEmailProcedure.params, Resend_SendEmailProcedure.returnType, "resend.sendEmail"), + __procedureSchema("resend.set_resend_config", Resend_SetResendConfigProcedure.params, Resend_SetResendConfigProcedure.returnType, "resend.setResendConfig"), + __procedureSchema("rate_limit.run_sweep", RateLimit_RunSweepProcedure.params, RateLimit_RunSweepProcedure.returnType, "rateLimit.runSweep"), +); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: "2.11.0" 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 = { + myDispatchDeliveryEvents: __qb.myDispatchDeliveryEvents, + myDispatchEmails: __qb.myDispatchEmails, + rateLimit: { + rateLimitConfig: __qb["rate_limit.rate_limit_config"], + adminRateLimitBuckets: __qb["rate_limit.admin_rate_limit_buckets"], + }, +} as const; + +/** The reducers available in this remote SpacetimeDB module. */ +const __reducerAccessors = __convertToAccessorMap(reducersSchema.reducersType.reducers); +export const reducers = { + rateLimit: { + addRateLimitAdmin: __reducerAccessors["rateLimit.addRateLimitAdmin"], + removeRateLimitAdmin: __reducerAccessors["rateLimit.removeRateLimitAdmin"], + resetBuckets: __reducerAccessors["rateLimit.resetBuckets"], + updateConfig: __reducerAccessors["rateLimit.updateConfig"], + }, + resend: { + ingestResendWebhook: __reducerAccessors["resend.ingestResendWebhook"], + replayWebhookEvent: __reducerAccessors["resend.replayWebhookEvent"], + }, +} as const; + +/** The procedures available in this remote SpacetimeDB module. */ +const __procedureAccessors = __convertToAccessorMap(proceduresSchema.procedures); +export const procedures = { + clearDispatches: __procedureAccessors.clearDispatches, + deleteDispatch: __procedureAccessors.deleteDispatch, + sendDispatch: __procedureAccessors.sendDispatch, + setDispatchPolicy: __procedureAccessors.setDispatchPolicy, + rateLimit: { + runSweep: __procedureAccessors["rateLimit.runSweep"], + }, + resend: { + addAdminIdentity: __procedureAccessors["resend.addAdminIdentity"], + cancelEmail: __procedureAccessors["resend.cancelEmail"], + getEmail: __procedureAccessors["resend.getEmail"], + getResendConfigStatus: __procedureAccessors["resend.getResendConfigStatus"], + getWebhookEvent: __procedureAccessors["resend.getWebhookEvent"], + listDeliveryEventsForEmail: __procedureAccessors["resend.listDeliveryEventsForEmail"], + listEmailsByOrgId: __procedureAccessors["resend.listEmailsByOrgId"], + listEmailsByStatus: __procedureAccessors["resend.listEmailsByStatus"], + listEmailsByUserId: __procedureAccessors["resend.listEmailsByUserId"], + removeAdminIdentity: __procedureAccessors["resend.removeAdminIdentity"], + resendApiRequest: __procedureAccessors["resend.resendApiRequest"], + sendEmail: __procedureAccessors["resend.sendEmail"], + setResendConfig: __procedureAccessors["resend.setResendConfig"], + }, +} 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-resend-ts/example/src/module_bindings/my_dispatch_delivery_events_table.ts b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_delivery_events_table.ts new file mode 100644 index 00000000000..bcd9654503f --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_delivery_events_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({ + eventId: __t.string().primaryKey().name("event_id"), + resendId: __t.string().name("resend_id"), + eventType: __t.string().name("event_type"), + createdAtIso: __t.string().name("created_at_iso"), + detailJson: __t.option(__t.string()).name("detail_json"), + insertedAt: __t.timestamp().name("inserted_at"), +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/my_dispatch_emails_table.ts b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_emails_table.ts new file mode 100644 index 00000000000..da3ee29f660 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_emails_table.ts @@ -0,0 +1,46 @@ +// 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 { + EmailStatus, +} from "./types"; + + +export default __t.row({ + resendId: __t.string().primaryKey().name("resend_id"), + fromAddress: __t.string().name("from_address"), + toAddressesJson: __t.string().name("to_addresses_json"), + subject: __t.option(__t.string()), + get status() { + return EmailStatus; + }, + lastError: __t.option(__t.string()).name("last_error"), + bouncedAt: __t.option(__t.timestamp()).name("bounced_at"), + bounceJson: __t.option(__t.string()).name("bounce_json"), + failedAt: __t.option(__t.timestamp()).name("failed_at"), + failureReason: __t.option(__t.string()).name("failure_reason"), + complained: __t.bool(), + complainedAt: __t.option(__t.timestamp()).name("complained_at"), + opened: __t.bool(), + openedAt: __t.option(__t.timestamp()).name("opened_at"), + clicked: __t.bool(), + clickedAt: __t.option(__t.timestamp()).name("clicked_at"), + deliveredAt: __t.option(__t.timestamp()).name("delivered_at"), + sentAt: __t.option(__t.timestamp()).name("sent_at"), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + tagsJson: __t.option(__t.string()).name("tags_json"), + userId: __t.option(__t.string()).name("user_id"), + orgId: __t.option(__t.string()).name("org_id"), + createdAt: __t.timestamp().name("created_at"), + updatedAt: __t.timestamp().name("updated_at"), + statusUpdatedAt: __t.option(__t.timestamp()).name("status_updated_at"), +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/add_rate_limit_admin_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/add_rate_limit_admin_reducer.ts new file mode 100644 index 00000000000..e39846ca8d9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/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-resend-ts/example/src/module_bindings/rateLimit/admin_rate_limit_buckets_table.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/admin_rate_limit_buckets_table.ts new file mode 100644 index 00000000000..189f539a043 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/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-resend-ts/example/src/module_bindings/rateLimit/rate_limit_config_table.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/rate_limit_config_table.ts new file mode 100644 index 00000000000..66ffe86e399 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/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-resend-ts/example/src/module_bindings/rateLimit/remove_rate_limit_admin_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/remove_rate_limit_admin_reducer.ts new file mode 100644 index 00000000000..e39846ca8d9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/remove_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-resend-ts/example/src/module_bindings/rateLimit/reset_buckets_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/reset_buckets_reducer.ts new file mode 100644 index 00000000000..a7c5cc5274f --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/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-resend-ts/example/src/module_bindings/rateLimit/run_sweep_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/run_sweep_procedure.ts new file mode 100644 index 00000000000..9815c99eb38 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/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-resend-ts/example/src/module_bindings/rateLimit/types.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/types.ts new file mode 100644 index 00000000000..d14931b1fb9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/types.ts @@ -0,0 +1,44 @@ +// 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(), + addedAt: __t.timestamp(), +}); +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 RateLimitSweepTick = __t.object("RateLimitSweepTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), +}); +export type RateLimitSweepTick = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/update_config_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/update_config_reducer.ts new file mode 100644 index 00000000000..54fcf361af1 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/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-resend-ts/example/src/module_bindings/resend/add_admin_identity_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/add_admin_identity_procedure.ts new file mode 100644 index 00000000000..bfd93108ec4 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/add_admin_identity_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 = { + identity: __t.identity(), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/cancel_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/cancel_email_procedure.ts new file mode 100644 index 00000000000..ec778b46cd0 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/cancel_email_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 = { + resendId: __t.string(), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/get_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/get_email_procedure.ts new file mode 100644 index 00000000000..0744ed77aab --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/get_email_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 { + ResendEmail, +} from "./types"; + +export const params = { + resendId: __t.string(), +}; +export const returnType = __t.option(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/get_resend_config_status_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/get_resend_config_status_procedure.ts new file mode 100644 index 00000000000..badd9ab9cc8 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/get_resend_config_status_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 { + ResendConfigStatus, +} from "./types"; + +export const params = { +}; +export const returnType = ResendConfigStatus \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/get_webhook_event_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/get_webhook_event_procedure.ts new file mode 100644 index 00000000000..8421d69c668 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/get_webhook_event_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 { + ResendWebhookEvent, +} from "./types"; + +export const params = { + eventId: __t.string(), +}; +export const returnType = __t.option(ResendWebhookEvent) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/ingest_resend_webhook_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/resend/ingest_resend_webhook_reducer.ts new file mode 100644 index 00000000000..1e7afcc3703 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/ingest_resend_webhook_reducer.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"; + +export default { + eventId: __t.string(), + eventType: __t.string(), + payloadJson: __t.string(), + signatureHeader: __t.option(__t.string()), + timestampHeader: __t.option(__t.string()), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_delivery_events_for_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_delivery_events_for_email_procedure.ts new file mode 100644 index 00000000000..27a3a808053 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_delivery_events_for_email_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 { + ResendDeliveryEvent, +} from "./types"; + +export const params = { + resendId: __t.string(), +}; +export const returnType = __t.array(ResendDeliveryEvent) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_org_id_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_org_id_procedure.ts new file mode 100644 index 00000000000..cd1063291da --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_org_id_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 { + ResendEmail, +} from "./types"; + +export const params = { + orgId: __t.string(), +}; +export const returnType = __t.array(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_status_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_status_procedure.ts new file mode 100644 index 00000000000..c24fc71c444 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_status_procedure.ts @@ -0,0 +1,23 @@ +// 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 { + ResendEmail, + EmailStatus, +} from "./types"; + +export const params = { + get status() { + return EmailStatus; + }, +}; +export const returnType = __t.array(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_user_id_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_user_id_procedure.ts new file mode 100644 index 00000000000..f712b807b32 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_user_id_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 { + ResendEmail, +} from "./types"; + +export const params = { + userId: __t.string(), +}; +export const returnType = __t.array(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/remove_admin_identity_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/remove_admin_identity_procedure.ts new file mode 100644 index 00000000000..bfd93108ec4 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/remove_admin_identity_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 = { + identity: __t.identity(), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/replay_webhook_event_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/resend/replay_webhook_event_reducer.ts new file mode 100644 index 00000000000..590a453de82 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/replay_webhook_event_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 { + eventId: __t.string(), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/resend_api_request_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/resend_api_request_procedure.ts new file mode 100644 index 00000000000..aff60351ebf --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/resend_api_request_procedure.ts @@ -0,0 +1,23 @@ +// 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 { + ResendApiRequestResult, +} from "./types"; + +export const params = { + method: __t.string(), + path: __t.string(), + jsonBody: __t.option(__t.string()), + idempotencyKey: __t.option(__t.string()), +}; +export const returnType = ResendApiRequestResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/send_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/send_email_procedure.ts new file mode 100644 index 00000000000..67babe6715f --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/send_email_procedure.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"; + +import { + SendEmailResult, +} from "./types"; + +export const params = { + from: __t.option(__t.string()), + to: __t.array(__t.string()), + subject: __t.string(), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + cc: __t.option(__t.array(__t.string())), + bcc: __t.option(__t.array(__t.string())), + replyTo: __t.option(__t.array(__t.string())), + tagsJson: __t.option(__t.string()), + headersJson: __t.option(__t.string()), + scheduledAt: __t.option(__t.string()), + idempotencyKey: __t.option(__t.string()), +}; +export const returnType = SendEmailResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/set_resend_config_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/set_resend_config_procedure.ts new file mode 100644 index 00000000000..645c952bd4d --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/set_resend_config_procedure.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 const params = { + apiKey: __t.string(), + webhookSigningSecret: __t.option(__t.string()), + defaultFrom: __t.option(__t.string()), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/types.ts b/spacetime-resend-ts/example/src/module_bindings/resend/types.ts new file mode 100644 index 00000000000..505864052b1 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/types.ts @@ -0,0 +1,124 @@ +// 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"; + +// The tagged union or sum type for the algebraic type `EmailStatus`. +export const EmailStatus = __t.enum("EmailStatus", { + Queued: __t.unit(), + Sent: __t.unit(), + Delivered: __t.unit(), + DeliveryDelayed: __t.unit(), + Bounced: __t.unit(), + Failed: __t.unit(), + Cancelled: __t.unit(), +}); +export type EmailStatus = __Infer; + +export const ResendAdminIdentity = __t.object("ResendAdminIdentity", { + identity: __t.identity(), + addedAt: __t.timestamp(), +}); +export type ResendAdminIdentity = __Infer; + +export const ResendApiRequestResult = __t.object("ResendApiRequestResult", { + status: __t.u16(), + body: __t.string(), +}); +export type ResendApiRequestResult = __Infer; + +export const ResendConfig = __t.object("ResendConfig", { + singleton: __t.bool(), + apiKey: __t.string(), + webhookSigningSecret: __t.option(__t.string()), + defaultFrom: __t.option(__t.string()), + updatedAt: __t.timestamp(), +}); +export type ResendConfig = __Infer; + +export const ResendConfigStatus = __t.object("ResendConfigStatus", { + isConfigured: __t.bool(), + hasWebhookSecret: __t.bool(), + defaultFrom: __t.option(__t.string()), + apiKeyLength: __t.u16(), +}); +export type ResendConfigStatus = __Infer; + +export const ResendDeliveryEvent = __t.object("ResendDeliveryEvent", { + eventId: __t.string(), + resendId: __t.string(), + eventType: __t.string(), + createdAtIso: __t.string(), + detailJson: __t.option(__t.string()), + insertedAt: __t.timestamp(), +}); +export type ResendDeliveryEvent = __Infer; + +export const ResendEmail = __t.object("ResendEmail", { + resendId: __t.string(), + fromAddress: __t.string(), + toAddressesJson: __t.string(), + subject: __t.option(__t.string()), + get status() { + return EmailStatus; + }, + lastError: __t.option(__t.string()), + bouncedAt: __t.option(__t.timestamp()), + bounceJson: __t.option(__t.string()), + failedAt: __t.option(__t.timestamp()), + failureReason: __t.option(__t.string()), + complained: __t.bool(), + complainedAt: __t.option(__t.timestamp()), + opened: __t.bool(), + openedAt: __t.option(__t.timestamp()), + clicked: __t.bool(), + clickedAt: __t.option(__t.timestamp()), + deliveredAt: __t.option(__t.timestamp()), + sentAt: __t.option(__t.timestamp()), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + tagsJson: __t.option(__t.string()), + userId: __t.option(__t.string()), + orgId: __t.option(__t.string()), + createdAt: __t.timestamp(), + updatedAt: __t.timestamp(), + statusUpdatedAt: __t.option(__t.timestamp()), +}); +export type ResendEmail = __Infer; + +export const ResendWebhookEvent = __t.object("ResendWebhookEvent", { + eventId: __t.string(), + eventType: __t.string(), + payloadJson: __t.string(), + signatureHeader: __t.option(__t.string()), + timestampHeader: __t.option(__t.string()), + get status() { + return WebhookEventStatus; + }, + errorMessage: __t.option(__t.string()), + receivedAt: __t.timestamp(), + processedAt: __t.option(__t.timestamp()), +}); +export type ResendWebhookEvent = __Infer; + +export const SendEmailResult = __t.object("SendEmailResult", { + resendId: __t.string(), +}); +export type SendEmailResult = __Infer; + +// The tagged union or sum type for the algebraic type `WebhookEventStatus`. +export const WebhookEventStatus = __t.enum("WebhookEventStatus", { + Received: __t.unit(), + Processed: __t.unit(), + Ignored: __t.unit(), + Failed: __t.unit(), +}); +export type WebhookEventStatus = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/send_dispatch_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/send_dispatch_procedure.ts new file mode 100644 index 00000000000..5a200f044d9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/send_dispatch_procedure.ts @@ -0,0 +1,22 @@ +// 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 { + DispatchSendResult, +} from "./types"; + +export const params = { + to: __t.string(), + subject: __t.string(), + message: __t.string(), +}; +export const returnType = DispatchSendResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/set_dispatch_policy_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/set_dispatch_policy_procedure.ts new file mode 100644 index 00000000000..d27751fdf5d --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/set_dispatch_policy_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 = { + allowedRecipientsJson: __t.string(), +}; +export const returnType = __t.bool() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/types.ts b/spacetime-resend-ts/example/src/module_bindings/types.ts new file mode 100644 index 00000000000..3a76237db76 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/types.ts @@ -0,0 +1,97 @@ +// 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 DispatchDeleteResult = __t.object("DispatchDeleteResult", { + ok: __t.bool(), + removed: __t.u32(), +}); +export type DispatchDeleteResult = __Infer; + +export const DispatchPolicy = __t.object("DispatchPolicy", { + singleton: __t.bool(), + allowedRecipientsJson: __t.string(), + updatedAt: __t.timestamp(), +}); +export type DispatchPolicy = __Infer; + +export const DispatchSendResult = __t.object("DispatchSendResult", { + ok: __t.bool(), + resendId: __t.option(__t.string()), + message: __t.string(), +}); +export type DispatchSendResult = __Infer; + +// The tagged union or sum type for the algebraic type `EmailStatus`. +export const EmailStatus = __t.enum("EmailStatus", { + Queued: __t.unit(), + Sent: __t.unit(), + Delivered: __t.unit(), + DeliveryDelayed: __t.unit(), + Bounced: __t.unit(), + Failed: __t.unit(), + Cancelled: __t.unit(), +}); +export type EmailStatus = __Infer; + +export const MyDispatchDeliveryEvents = __t.object("MyDispatchDeliveryEvents", {}); +export type MyDispatchDeliveryEvents = __Infer; + +export const MyDispatchEmails = __t.object("MyDispatchEmails", {}); +export type MyDispatchEmails = __Infer; + +export const RemovedDispatch = __t.object("RemovedDispatch", { + resendId: __t.string(), +}); +export type RemovedDispatch = __Infer; + +export const ResendDeliveryEvent = __t.object("ResendDeliveryEvent", { + eventId: __t.string(), + resendId: __t.string(), + eventType: __t.string(), + createdAtIso: __t.string(), + detailJson: __t.option(__t.string()), + insertedAt: __t.timestamp(), +}); +export type ResendDeliveryEvent = __Infer; + +export const ResendEmail = __t.object("ResendEmail", { + resendId: __t.string(), + fromAddress: __t.string(), + toAddressesJson: __t.string(), + subject: __t.option(__t.string()), + get status() { + return EmailStatus; + }, + lastError: __t.option(__t.string()), + bouncedAt: __t.option(__t.timestamp()), + bounceJson: __t.option(__t.string()), + failedAt: __t.option(__t.timestamp()), + failureReason: __t.option(__t.string()), + complained: __t.bool(), + complainedAt: __t.option(__t.timestamp()), + opened: __t.bool(), + openedAt: __t.option(__t.timestamp()), + clicked: __t.bool(), + clickedAt: __t.option(__t.timestamp()), + deliveredAt: __t.option(__t.timestamp()), + sentAt: __t.option(__t.timestamp()), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + tagsJson: __t.option(__t.string()), + userId: __t.option(__t.string()), + orgId: __t.option(__t.string()), + createdAt: __t.timestamp(), + updatedAt: __t.timestamp(), + statusUpdatedAt: __t.option(__t.timestamp()), +}); +export type ResendEmail = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/types/procedures.ts b/spacetime-resend-ts/example/src/module_bindings/types/procedures.ts new file mode 100644 index 00000000000..13622fae9a4 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/types/procedures.ts @@ -0,0 +1,22 @@ +// 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 ClearDispatchesProcedure from "../clear_dispatches_procedure"; +import * as DeleteDispatchProcedure from "../delete_dispatch_procedure"; +import * as SendDispatchProcedure from "../send_dispatch_procedure"; +import * as SetDispatchPolicyProcedure from "../set_dispatch_policy_procedure"; + +export type ClearDispatchesArgs = __Infer; +export type ClearDispatchesResult = __Infer; +export type DeleteDispatchArgs = __Infer; +export type DeleteDispatchResult = __Infer; +export type SendDispatchArgs = __Infer; +export type SendDispatchResult = __Infer; +export type SetDispatchPolicyArgs = __Infer; +export type SetDispatchPolicyResult = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/types/reducers.ts b/spacetime-resend-ts/example/src/module_bindings/types/reducers.ts new file mode 100644 index 00000000000..c701027cbf1 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/types/reducers.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 reducer arg schemas + + diff --git a/spacetime-resend-ts/example/tsconfig.json b/spacetime-resend-ts/example/tsconfig.json new file mode 100644 index 00000000000..8e5e2bbddf0 --- /dev/null +++ b/spacetime-resend-ts/example/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "allowImportingTsExtensions": false, + "esModuleInterop": true, + "isolatedModules": true, + "useDefineForClassFields": true, + "lib": ["ES2022", "DOM", "DOM.Iterable"] + }, + "include": ["src/**/*.ts", "scripts/**/*.ts", "server.ts"], + "exclude": ["node_modules", "public", "dist"] +} diff --git a/spacetime-resend-ts/package.json b/spacetime-resend-ts/package.json new file mode 100644 index 00000000000..ec58ab75835 --- /dev/null +++ b/spacetime-resend-ts/package.json @@ -0,0 +1,86 @@ +{ + "name": "@spacetimedb/resend", + "description": "Resend email delivery, webhook verification, and event storage 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": [ + "dist", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./submodule": { + "types": "./dist/submodule.d.ts", + "default": "./dist/submodule.js" + } + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-resend-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-resend-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "resend", + "email", + "webhooks" + ], + "scripts": { + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "build:module": "spacetime build", + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "tsx scripts/test-unit.ts && node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test-webhooks.ts", + "spacetime:generate": "spacetime generate --lang typescript --out-dir ts-codegen", + "publish:module": "spacetime publish", + "publish:local": "spacetime publish --server local --yes spacetime-resend", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-resend", + "test:smoke": "tsx scripts/test-resend-smoke.ts", + "test:gate:local": "tsx scripts/test-resend-smoke.ts" + }, + "dependencies": { + "@spacetimedb/crypto": "workspace:^", + "valibot": "^1.4.2" + }, + "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-resend-ts/scripts/sys-abi-test-register.mjs b/spacetime-resend-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..30107456e71 --- /dev/null +++ b/spacetime-resend-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,27 @@ +import { register } from 'node:module'; + +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; + +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; + export function resolve(specifier, context, nextResolve) { + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-resend-ts/scripts/test-resend-smoke.ts b/spacetime-resend-ts/scripts/test-resend-smoke.ts new file mode 100644 index 00000000000..0b62390a589 --- /dev/null +++ b/spacetime-resend-ts/scripts/test-resend-smoke.ts @@ -0,0 +1,602 @@ +// Synthetic signed events only; no provider requests. Add --example to test the native HTTP route. + +import { spawn } from 'node:child_process'; +import { createHmac } from 'node:crypto'; + +type Options = { + server: string; + database: string; + skipBuildPublish: boolean; + example: boolean; +}; + +function parseArgs(argv: string[]): Options { + const opts: Options = { + server: 'http://127.0.0.1:3000', + // Dedicated DB so smoke test never overwrites the dev module's real config. + database: 'resend-ts-smoke-test', + skipBuildPublish: false, + example: false, + }; + for (let i = 0; i < argv.length; i++) { + const raw = argv[i]!; + const flag = raw.replace(/^-+/, '').toLowerCase(); + if (flag === 'skip-build-publish') opts.skipBuildPublish = true; + if (flag === 'example') opts.example = true; + if (flag === 'server') opts.server = argv[++i]!; + if (flag === 'database') opts.database = argv[++i]!; + } + return opts; +} + +function step(name: string) { + process.stdout.write(`\n==> ${name}\n`); +} + +function run( + cmd: string, + args: string[] +): Promise<{ code: number; stdout: string; stderr: string }> { + return new Promise(resolve => { + const child = spawn(cmd, args, { shell: false }); + let stdout = ''; + let stderr = ''; + child.stdout?.on('data', d => (stdout += String(d))); + child.stderr?.on('data', d => (stderr += String(d))); + child.on('close', code => resolve({ code: code ?? 1, stdout, stderr })); + child.on('error', err => + resolve({ code: 1, stdout, stderr: stderr + String(err) }) + ); + }); +} + +async function callReducer( + opts: Options, + name: string, + args: string[] +): Promise { + const result = await run('spacetime', [ + 'call', + '--server', + opts.server, + opts.database, + opts.example ? `resend.${name}` : name, + ...args, + ]); + if (result.code !== 0) { + throw new Error( + `spacetime call ${name} failed: code=${result.code}\nstderr: ${result.stderr}\nstdout: ${result.stdout}` + ); + } + return result.stdout; +} + +// Expects the call to fail. Returns combined stderr/stdout for assertion. +async function expectCallFails( + opts: Options, + name: string, + args: string[], + anonymous = false +): Promise { + const result = await run('spacetime', [ + 'call', + ...(anonymous ? ['--anonymous'] : []), + '--server', + opts.server, + opts.database, + opts.example ? `resend.${name}` : name, + ...args, + ]); + if (result.code === 0) { + throw new Error( + `expected ${name} to fail but it succeeded:\nstdout: ${result.stdout}` + ); + } + return result.stderr + result.stdout; +} + +function quote(s: string): string { + return JSON.stringify(s); +} + +function some(s: string): string { + return JSON.stringify({ some: s }); +} + +const RESEND_WEBHOOK_SECRET_RAW = 'resend_smoke_test_secret'; +const RESEND_WEBHOOK_SECRET = `whsec_${Buffer.from(RESEND_WEBHOOK_SECRET_RAW).toString('base64')}`; + +function svixSignature(args: { + eventId: string; + timestamp: string; + payloadJson: string; +}): string { + const digest = createHmac('sha256', RESEND_WEBHOOK_SECRET_RAW) + .update(`${args.eventId}.${args.timestamp}.${args.payloadJson}`) + .digest('base64'); + return `v1,${digest}`; +} + +async function ingestWebhook( + opts: Options, + eventId: string, + eventType: string, + payloadJson: string +) { + const timestamp = String(Math.floor(Date.now() / 1000)); + await callReducer(opts, 'ingest_resend_webhook', [ + quote(eventId), + quote(eventType), + quote(payloadJson), + some(svixSignature({ eventId, timestamp, payloadJson })), + some(timestamp), + ]); +} + +function eventPayload(args: { + type: string; + emailId: string; + from?: string; + to?: string[]; + subject?: string; + extra?: Record; + createdAt?: string; +}): string { + const data: Record = { + email_id: args.emailId, + created_at: '2026-05-04T00:00:00Z', + from: args.from ?? 'onboarding@resend.dev', + to: args.to ?? ['delivered@resend.dev'], + subject: args.subject ?? 'smoke test', + ...(args.extra ?? {}), + }; + return JSON.stringify({ + type: args.type, + created_at: args.createdAt ?? '2026-05-04T00:00:00Z', + data, + }); +} + +const EMAIL_STATUS = [ + 'Queued', + 'Sent', + 'Delivered', + 'DeliveryDelayed', + 'Bounced', + 'Failed', + 'Cancelled', +] as const; + +function emailStatus(rowText: string): string { + const parsed = JSON.parse(rowText); + const row = parsed?.[1]; + const variant = row?.[4]; + const tag = variant?.[0]; + if (typeof tag !== 'number' || tag < 0 || tag >= EMAIL_STATUS.length) { + throw new Error(`could not parse email status from row: ${rowText}`); + } + return EMAIL_STATUS[tag]!; +} + +const WEBHOOK_EVENT_STATUS = [ + 'Received', + 'Processed', + 'Ignored', + 'Failed', +] as const; + +function webhookEventStatus(rowText: string): string { + const parsed = JSON.parse(rowText); + const row = parsed?.[1]; + const variant = row?.[5]; + const tag = variant?.[0]; + if ( + typeof tag !== 'number' || + tag < 0 || + tag >= WEBHOOK_EVENT_STATUS.length + ) { + throw new Error( + `could not parse webhook event status from row: ${rowText}` + ); + } + return WEBHOOK_EVENT_STATUS[tag]!; +} + +async function main() { + const opts = parseArgs(process.argv.slice(2)); + // Unique run id so re-runs don't collide on idempotent webhook IDs. + const runId = Date.now().toString(36); + const evt = (suffix: string) => `evt_${runId}_${suffix}`; + const em = (suffix: string) => `em_${runId}_${suffix}`; + + if (!opts.skipBuildPublish) { + step('spacetime build'); + const modulePath = opts.example + ? ['--module-path', 'example/spacetimedb'] + : []; + const build = await run('spacetime', ['build', ...modulePath]); + if (build.code !== 0) { + process.stderr.write(build.stderr); + throw new Error('build failed'); + } + + step(`spacetime publish --server ${opts.server} ${opts.database}`); + const publish = await run('spacetime', [ + 'publish', + '--server', + opts.server, + '--yes', + '--delete-data', + ...modulePath, + opts.database, + ]); + if (publish.code !== 0) { + process.stderr.write(publish.stderr); + throw new Error('publish failed'); + } + } + + // Negative path: send_email refuses cleanly when config is not set. + step('negative: send_email before config, expect failure'); + const preBootstrap = await expectCallFails(opts, 'send_email', [ + 'null', + JSON.stringify(['delivered@resend.dev']), + quote('hello'), + some('

hello

'), + 'null', + 'null', + 'null', + 'null', + 'null', + 'null', + 'null', + 'null', + ]); + if (!preBootstrap.toLowerCase().includes('config')) { + throw new Error( + `expected error to mention config; got: ${preBootstrap.slice(0, 400)}` + ); + } + + step('set_resend_config'); + await callReducer(opts, 'set_resend_config', [ + quote('re_smoke_placeholder'), + some(RESEND_WEBHOOK_SECRET), + some('onboarding@resend.dev'), + ]); + + if (opts.example) { + step('HTTP rejects failed payloads on first delivery and redelivery'); + const eventId = evt('invalid_http'); + const payloadJson = JSON.stringify({ type: 'email.sent', data: {} }); + for (let attempt = 0; attempt < 2; attempt++) { + const timestamp = String(Math.floor(Date.now() / 1000)); + const response = await fetch( + `${opts.server}/v1/database/${opts.database}/route/webhook/resend`, + { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'svix-id': eventId, + 'svix-timestamp': timestamp, + 'svix-signature': svixSignature({ + eventId, + timestamp, + payloadJson, + }), + }, + body: payloadJson, + } + ); + if (response.status !== 400) + throw new Error( + `expected invalid payload HTTP 400 on attempt ${attempt}, got ${response.status}: ${await response.text()}` + ); + } + } + + step('negative: anonymous callers cannot query email state'); + const unauthorized = await expectCallFails( + opts, + 'get_email', + [quote(em('a'))], + true + ); + if (!unauthorized.toLowerCase().includes('not_authorized')) { + throw new Error( + `expected get_email to reject a non-admin caller: ${unauthorized.slice(0, 400)}` + ); + } + + step('negative: signed webhook type must match supplied event type'); + const mismatchEventId = evt('metadata_mismatch'); + const mismatchPayload = eventPayload({ + type: 'email.delivered', + emailId: em('metadata_mismatch'), + }); + const mismatchTimestamp = String(Math.floor(Date.now() / 1000)); + const mismatch = await expectCallFails(opts, 'ingest_resend_webhook', [ + quote(mismatchEventId), + quote('email.bounced'), + quote(mismatchPayload), + some( + svixSignature({ + eventId: mismatchEventId, + timestamp: mismatchTimestamp, + payloadJson: mismatchPayload, + }) + ), + some(mismatchTimestamp), + ]); + if (!mismatch.toLowerCase().includes('metadata')) { + throw new Error( + `expected signed metadata mismatch failure: ${mismatch.slice(0, 400)}` + ); + } + + step('reducer keeps a Failed row for an invalid signed payload'); + const invalidEventId = evt('invalid_reducer'); + await ingestWebhook( + opts, + invalidEventId, + 'email.sent', + JSON.stringify({ type: 'email.sent', data: {} }) + ); + const readInvalidEvent = () => + callReducer(opts, 'get_webhook_event', [quote(invalidEventId)]); + let stored = await readInvalidEvent(); + if (webhookEventStatus(stored) !== 'Failed') + throw new Error(`expected Failed webhook row after ingest: ${stored}`); + await callReducer(opts, 'replay_webhook_event', [quote(invalidEventId)]); + stored = await readInvalidEvent(); + if (webhookEventStatus(stored) !== 'Failed') + throw new Error(`expected Failed webhook row after replay: ${stored}`); + + step('signed event types the submodule does not handle are acknowledged'); + await ingestWebhook( + opts, + evt('contact'), + 'contact.created', + JSON.stringify({ + type: 'contact.created', + created_at: '2026-05-04T00:00:00Z', + data: { id: 'contact_smoke' }, + }) + ); + + // Email A happy path: queued -> sent -> delivered, then flag overlays must not roll status back. + step(`ingest email.sent for ${em('a')}`); + await ingestWebhook( + opts, + evt('a'), + 'email.sent', + eventPayload({ type: 'email.sent', emailId: em('a') }) + ); + + step(`ingest email.delivered for ${em('a')}`); + await ingestWebhook( + opts, + evt('b'), + 'email.delivered', + eventPayload({ type: 'email.delivered', emailId: em('a') }) + ); + + step(`verify status=delivered for ${em('a')}`); + let row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`expected delivered for ${em('a')}, got: ${row}`); + } + + step(`ingest email.complained for ${em('a')} (flag, must NOT change status)`); + await ingestWebhook( + opts, + evt('e'), + 'email.complained', + eventPayload({ type: 'email.complained', emailId: em('a') }) + ); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`complained should not flip status: ${row}`); + } + + step(`ingest email.opened for ${em('a')} (flag)`); + await ingestWebhook( + opts, + evt('g'), + 'email.opened', + eventPayload({ type: 'email.opened', emailId: em('a') }) + ); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`opened should not flip status: ${row}`); + } + + step(`ingest email.clicked for ${em('a')} (flag + detail captured)`); + await ingestWebhook( + opts, + evt('h'), + 'email.clicked', + eventPayload({ + type: 'email.clicked', + emailId: em('a'), + extra: { + click: { + ipAddress: '203.0.113.42', + link: 'https://spacetimedb.com', + timestamp: '2026-05-04T00:00:00Z', + userAgent: 'Mozilla/5.0 (smoke-test)', + }, + }, + }) + ); + const clickEvents = await callReducer( + opts, + 'list_delivery_events_for_email', + [quote(em('a'))] + ); + const clickRows: unknown = JSON.parse(clickEvents); + const clickRow = Array.isArray(clickRows) + ? clickRows.find(row => Array.isArray(row) && row[2] === 'email.clicked') + : undefined; + if (!clickRow) { + throw new Error(`expected click event in delivery log: ${clickEvents}`); + } + const detailOption = Array.isArray(clickRow) ? clickRow[4] : undefined; + const detailJson = + Array.isArray(detailOption) && + detailOption[0] === 0 && + typeof detailOption[1] === 'string' + ? detailOption[1] + : undefined; + const clickDetail = detailJson ? JSON.parse(detailJson) : undefined; + if (clickDetail?.link !== 'https://spacetimedb.com') { + throw new Error(`expected click detail (link) preserved: ${clickEvents}`); + } + + // Email C bounce path with structured detail. + step(`ingest email.bounced for ${em('c')}`); + await ingestWebhook( + opts, + evt('c'), + 'email.bounced', + eventPayload({ + type: 'email.bounced', + emailId: em('c'), + to: ['bounced@resend.dev'], + extra: { + bounce: { + message: 'Mailbox does not exist', + subType: 'NoEmail', + type: 'Permanent', + }, + }, + }) + ); + const bouncedRow = await callReducer(opts, 'get_email', [quote(em('c'))]); + if (emailStatus(bouncedRow) !== 'Bounced') { + throw new Error(`expected bounced for ${em('c')}: ${bouncedRow}`); + } + if (!bouncedRow.includes('Mailbox does not exist')) { + throw new Error(`expected bounce reason in row: ${bouncedRow}`); + } + + step('late sent, delayed, and failed events do not undo a bounce'); + for (const type of ['email.sent', 'email.delivery_delayed']) { + await ingestWebhook( + opts, + evt(`late_${type}`), + type, + eventPayload({ + type, + emailId: em('c'), + createdAt: '2026-05-03T23:59:00Z', + }) + ); + const current = await callReducer(opts, 'get_email', [quote(em('c'))]); + if (emailStatus(current) !== 'Bounced') + throw new Error(`late ${type} changed bounce: ${current}`); + } + await ingestWebhook( + opts, + evt('late_failed'), + 'email.failed', + eventPayload({ + type: 'email.failed', + emailId: em('c'), + extra: { failed: { reason: 'late failure' } }, + }) + ); + const afterLateFailure = await callReducer(opts, 'get_email', [ + quote(em('c')), + ]); + if ( + emailStatus(afterLateFailure) !== 'Bounced' || + afterLateFailure.includes('late failure') + ) + throw new Error(`late failure changed bounce: ${afterLateFailure}`); + await callReducer(opts, 'replay_webhook_event', [ + quote(evt('late_email.sent')), + ]); + if ( + emailStatus(await callReducer(opts, 'get_email', [quote(em('c'))])) !== + 'Bounced' + ) { + throw new Error('administrative replay regressed email status'); + } + + // Email D delivery_delayed status path. + step(`ingest email.delivery_delayed for ${em('d')}`); + await ingestWebhook( + opts, + evt('d'), + 'email.delivery_delayed', + eventPayload({ type: 'email.delivery_delayed', emailId: em('d') }) + ); + const delayed = await callReducer(opts, 'get_email', [quote(em('d'))]); + if (emailStatus(delayed) !== 'DeliveryDelayed') { + throw new Error(`expected delivery_delayed for ${em('d')}: ${delayed}`); + } + + // Email F failed status with reason. + step(`ingest email.failed for ${em('f')}`); + await ingestWebhook( + opts, + evt('f'), + 'email.failed', + eventPayload({ + type: 'email.failed', + emailId: em('f'), + extra: { failed: { reason: 'rate limited by destination MTA' } }, + }) + ); + const failedRow = await callReducer(opts, 'get_email', [quote(em('f'))]); + if (emailStatus(failedRow) !== 'Failed') { + throw new Error(`expected failed for ${em('f')}: ${failedRow}`); + } + if (!failedRow.includes('rate limited')) { + throw new Error(`expected failure reason in row: ${failedRow}`); + } + + // Idempotency + replay. + step( + `verify idempotency: re-ingest ${evt('a')} (already processed, should no-op)` + ); + await ingestWebhook( + opts, + evt('a'), + 'email.sent', + eventPayload({ type: 'email.sent', emailId: em('a') }) + ); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`replay broke status: ${row}`); + } + + step(`replay_webhook_event re-applies ${evt('b')} (status stays delivered)`); + await callReducer(opts, 'replay_webhook_event', [quote(evt('b'))]); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`replay reducer altered state: ${row}`); + } + + step('negative: replay unknown event_id, expect failure'); + const replayMissing = await expectCallFails(opts, 'replay_webhook_event', [ + quote('evt_does_not_exist_xyz'), + ]); + if (!replayMissing.toLowerCase().includes('not_found')) { + throw new Error( + `expected not_found error; got: ${replayMissing.slice(0, 400)}` + ); + } + + step( + 'done: signed webhook, status, idempotency, replay, and rejection checks passed' + ); +} + +main().catch(err => { + process.stderr.write( + `\nSMOKE TEST FAILED: ${err instanceof Error ? err.message : String(err)}\n` + ); + process.exit(1); +}); diff --git a/spacetime-resend-ts/scripts/test-unit.ts b/spacetime-resend-ts/scripts/test-unit.ts new file mode 100644 index 00000000000..01ac89d0cbf --- /dev/null +++ b/spacetime-resend-ts/scripts/test-unit.ts @@ -0,0 +1,98 @@ +import * as assert from 'node:assert/strict'; +import { buildResendHttpRequest } from '../src/submodule/request'; +import { validateEmailInput } from '../src/submodule/email-input'; +import { parseResendEventType } from '../src/submodule/webhook-metadata'; + +assert.equal( + parseResendEventType('{"type":"email.delivered","data":{}}'), + 'email.delivered' +); +assert.equal(parseResendEventType('{"type":"","data":{}}'), undefined); +assert.equal(parseResendEventType('{"data":{}}'), undefined); +assert.equal(parseResendEventType('{bad json'), undefined); +assert.equal(parseResendEventType('[]'), undefined); + +const request = buildResendHttpRequest({ + method: 'post', + path: '/emails', + apiKey: 're_test_secret', + jsonBody: '{"to":["user@example.com"]}', + idempotencyKey: 'email-user-1', +}); +assert.equal(request.url, 'https://api.resend.com/emails'); +assert.equal(request.method, 'POST'); +assert.equal(request.headers.Authorization, 'Bearer re_test_secret'); +assert.throws( + () => + buildResendHttpRequest({ + method: 'GET', + path: 'https://attacker.example/collect', + apiKey: 're_test_secret', + jsonBody: undefined, + idempotencyKey: undefined, + }), + /resend\.request_path_invalid/ +); +assert.throws( + () => + buildResendHttpRequest({ + method: 'GET', + path: '/emails\u007fblocked', + apiKey: 're_test_secret', + jsonBody: undefined, + idempotencyKey: undefined, + }), + /resend\.request_path_invalid/ +); +assert.throws( + () => + buildResendHttpRequest({ + method: 'TRACE', + path: '/emails', + apiKey: 're_test_secret', + jsonBody: undefined, + idempotencyKey: undefined, + }), + /resend\.request_method_invalid/ +); + +assert.doesNotThrow(() => + validateEmailInput({ + to: ['user@example.com'], + subject: 'Welcome', + text: 'Hello', + }) +); +assert.throws( + () => validateEmailInput({ to: [], subject: 'Welcome', text: 'Hello' }), + /resend\.send_email_no_recipients/ +); +assert.throws( + () => + validateEmailInput({ + to: ['user@example.com\u007fblocked'], + subject: 'Welcome', + text: 'Hello', + }), + /resend\.to_invalid_address/ +); +assert.throws( + () => + validateEmailInput({ + to: ['user@example.com'], + subject: 'Welcome\r\nx-injected: yes', + text: 'Hello', + }), + /resend\.send_email_invalid_subject/ +); +assert.throws( + () => + validateEmailInput({ + to: Array.from({ length: 101 }, (_, index) => `user${index}@example.com`), + subject: 'Welcome', + text: 'Hello', + }), + /resend\.to_too_many/ +); + +console.log('resend unit tests passed'); diff --git a/spacetime-resend-ts/scripts/test-webhooks.ts b/spacetime-resend-ts/scripts/test-webhooks.ts new file mode 100644 index 00000000000..85b3c54bfa0 --- /dev/null +++ b/spacetime-resend-ts/scripts/test-webhooks.ts @@ -0,0 +1,115 @@ +import * as assert from 'node:assert/strict'; +import { createHmac } from 'node:crypto'; +import { Timestamp } from 'spacetimedb'; +import { SenderError } from 'spacetimedb/server'; +import { + ingestResendWebhook, + makeResendWebhookHandler, +} from '../src/submodule/webhooks'; + +const secretRaw = 'resend_unit_test_secret'; +const secret = `whsec_${Buffer.from(secretRaw).toString('base64')}`; +const nowSeconds = 1_800_000_000; +const timestamp = String(nowSeconds); +const payloadJson = JSON.stringify({ + type: 'contact.created', + created_at: '2027-01-15T08:00:00Z', + data: { id: 'contact_1' }, +}); + +// Signed and handled, but fails payload validation. +const invalidPayloadJson = JSON.stringify({ + type: 'email.sent', + created_at: '2027-01-15T08:00:00Z', + data: {}, +}); + +function sign(eventId: string, body = payloadJson): string { + const digest = createHmac('sha256', secretRaw) + .update(`${eventId}.${timestamp}.${body}`) + .digest('base64'); + return `v1,${digest}`; +} + +// The mock context implements only the tables these paths read and write. +type EventRow = { eventId: string; status: { tag: string } }; +const webhookEvents = new Map(); +const tx = { + timestamp: new Timestamp(BigInt(nowSeconds) * 1_000_000n), + db: { + resendConfig: { + singleton: { find: () => ({ webhookSigningSecret: secret }) }, + }, + resendWebhookEvent: { + eventId: { + find: (id: string) => webhookEvents.get(id), + update: (row: EventRow) => webhookEvents.set(row.eventId, row), + }, + insert: (row: EventRow) => webhookEvents.set(row.eventId, row), + }, + }, +}; + +const handler = makeResendWebhookHandler(); +function post(eventId: string, signature: string, body = payloadJson) { + const headers = new Map([ + ['svix-id', eventId], + ['svix-timestamp', timestamp], + ['svix-signature', signature], + ]); + const req = { + method: 'POST', + headers: { get: (name: string) => headers.get(name) ?? null }, + text: () => body, + }; + return handler( + { withTx: (fn: (ctx: typeof tx) => unknown) => fn(tx) } as never, + req as never + ); +} + +const rejected = post('evt_bad_http', sign('evt_other')); +assert.equal(rejected.status, 401); +assert.match(rejected.text(), /resend\.webhook_signature_mismatch/); +assert.equal(webhookEvents.size, 0); + +assert.equal(post('evt_good_http', sign('evt_good_http')).status, 200); +assert.ok(webhookEvents.has('evt_good_http')); + +const invalidHttp = post( + 'evt_invalid_http', + sign('evt_invalid_http', invalidPayloadJson), + invalidPayloadJson +); +assert.equal(invalidHttp.status, 400); +assert.match(invalidHttp.text(), /resend\.webhook_payload_invalid/); +assert.equal(webhookEvents.get('evt_invalid_http')?.status.tag, 'Failed'); + +const ingest = (eventId: string, signature: string, body = payloadJson) => + ingestResendWebhook(tx as never, { + eventId, + eventType: JSON.parse(body).type, + payloadJson: body, + signatureHeader: signature, + timestampHeader: timestamp, + }); + +assert.throws( + () => ingest('evt_bad_reducer', sign('evt_other')), + (error: unknown) => + error instanceof SenderError && + /resend\.webhook_signature_mismatch/.test(error.message) +); +assert.ok(!webhookEvents.has('evt_bad_reducer')); +ingest('evt_good_reducer', sign('evt_good_reducer')); +assert.ok(webhookEvents.has('evt_good_reducer')); + +// The reducer returns so the Failed row commits. +ingest( + 'evt_invalid_reducer', + sign('evt_invalid_reducer', invalidPayloadJson), + invalidPayloadJson +); +assert.equal(webhookEvents.get('evt_invalid_reducer')?.status.tag, 'Failed'); + +process.stdout.write('resend webhook tests passed\n'); diff --git a/spacetime-resend-ts/src/index.ts b/spacetime-resend-ts/src/index.ts new file mode 100644 index 00000000000..72d8ebde3b1 --- /dev/null +++ b/spacetime-resend-ts/src/index.ts @@ -0,0 +1,19 @@ +export { default, init } from './submodule/schema.js'; +export { + ingestResendWebhook, + replayWebhookEvent, +} from './submodule/webhooks.js'; + +export { setResendConfig, getResendConfigStatus } from './submodule/config.js'; +export { addAdminIdentity, removeAdminIdentity } from './submodule/auth.js'; +export { + cancelEmail, + getEmail, + getWebhookEvent, + listDeliveryEventsForEmail, + listEmailsByOrgId, + listEmailsByStatus, + listEmailsByUserId, + resendApiRequest, + sendEmail, +} from './submodule/operations.js'; diff --git a/spacetime-resend-ts/src/submodule.ts b/spacetime-resend-ts/src/submodule.ts new file mode 100644 index 00000000000..6df49341a3f --- /dev/null +++ b/spacetime-resend-ts/src/submodule.ts @@ -0,0 +1,30 @@ +export { default } from './submodule/schema.js'; +export { + resendDeliveryEventTable, + resendEmailTable, + t, +} from './submodule/schema.js'; +export { install } from './submodule/install.js'; +export { errors } from './submodule/errors.js'; +export { + ingestResendWebhook, + replayWebhookEvent, + makeResendWebhookHandler, + type ResendWebhookIngestArgs, +} from './submodule/webhooks.js'; +export { + sendEmailRequest, + sendEmail, + cancelEmail, + getEmail, + getWebhookEvent, + listEmailsByUserId, + listEmailsByOrgId, + listEmailsByStatus, + listDeliveryEventsForEmail, + resendApiRequest, + type SendEmailArgs, +} from './submodule/operations.js'; + +export { setResendConfig, getResendConfigStatus } from './submodule/config.js'; +export { addAdminIdentity, removeAdminIdentity } from './submodule/auth.js'; diff --git a/spacetime-resend-ts/src/submodule/auth.ts b/spacetime-resend-ts/src/submodule/auth.ts new file mode 100644 index 00000000000..83d435636b0 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/auth.ts @@ -0,0 +1,67 @@ +import { + spacetimedb, + t, + type ProcedureModuleCtx, + type WriteCtx, +} from './schema.js'; +import { throwSenderError } from './validation.js'; +import { errors } from './errors.js'; + +// Admin gate. Fresh publishes seed the owner via init. Public submodule calls +// never bootstrap admin state from "first caller wins". Procedure callers must +// pass the outer ctx.sender explicitly; transaction ctx may not carry sender. +type Sender = WriteCtx['sender']; + +export type AdminVerdict = 'admin' | 'denied'; + +export function isAdmin(ctx: WriteCtx, sender: Sender): boolean { + return ctx.db.resendAdminIdentity.identity.find(sender) != null; +} + +export function adminVerdict(ctx: WriteCtx, sender: Sender): AdminVerdict { + return isAdmin(ctx, sender) ? 'admin' : 'denied'; +} + +export function denyIfNotAdmin(verdict: AdminVerdict): void { + if (verdict === 'denied') throwSenderError(errors.notAuthorized); +} + +export function requireAdmin(ctx: WriteCtx, sender: Sender): void { + if (!isAdmin(ctx, sender)) throwSenderError(errors.notAuthorized); +} + +export const addAdminIdentity = spacetimedb.procedure( + { identity: t.identity() }, + t.unit(), + (ctx: ProcedureModuleCtx, { identity }) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + ctx.withTx(tx => { + if (tx.db.resendAdminIdentity.identity.find(identity) == null) { + tx.db.resendAdminIdentity.insert({ + identity, + addedAt: ctx.timestamp, + }); + } + }); + return {}; + } +); + +export const removeAdminIdentity = spacetimedb.procedure( + { identity: t.identity() }, + t.unit(), + (ctx: ProcedureModuleCtx, { identity }) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + ctx.withTx(tx => { + const existing = tx.db.resendAdminIdentity.identity.find(identity); + if (!existing) return; + if (tx.db.resendAdminIdentity.count() <= 1n) { + throwSenderError(errors.cannotRemoveLastAdmin); + } + tx.db.resendAdminIdentity.delete(existing); + }); + return {}; + } +); diff --git a/spacetime-resend-ts/src/submodule/config.ts b/spacetime-resend-ts/src/submodule/config.ts new file mode 100644 index 00000000000..0f1e546f60c --- /dev/null +++ b/spacetime-resend-ts/src/submodule/config.ts @@ -0,0 +1,108 @@ +import { + spacetimedb, + t, + type ProcedureModuleCtx, + type WriteCtx, +} from './schema.js'; +import { adminVerdict, denyIfNotAdmin } from './auth.js'; +import { throwSenderError } from './validation.js'; +import { errors } from './errors.js'; + +export type ResendConfig = { + apiKey: string; + webhookSigningSecret: string | undefined; + defaultFrom: string | undefined; +}; + +export function loadConfigOrThrow(ctx: WriteCtx): ResendConfig { + const row = ctx.db.resendConfig.singleton.find(true); + if (!row) { + throwSenderError( + `${errors.configNotSet}: call set_resend_config(...) first` + ); + } + return { + apiKey: row.apiKey, + webhookSigningSecret: row.webhookSigningSecret, + defaultFrom: row.defaultFrom, + }; +} + +export function loadConfigOrThrowFromProcedure( + ctx: ProcedureModuleCtx +): ResendConfig { + return ctx.withTx(tx => loadConfigOrThrow(tx)); +} + +function upsertConfig( + ctx: WriteCtx, + args: { + apiKey: string; + webhookSigningSecret?: string | undefined; + defaultFrom?: string | undefined; + } +) { + const existing = ctx.db.resendConfig.singleton.find(true); + const row = { + singleton: true, + apiKey: args.apiKey, + webhookSigningSecret: + args.webhookSigningSecret ?? existing?.webhookSigningSecret, + defaultFrom: args.defaultFrom ?? existing?.defaultFrom, + updatedAt: ctx.timestamp, + }; + if (!existing) { + ctx.db.resendConfig.insert(row); + return; + } + ctx.db.resendConfig.singleton.update(row); +} + +// Requires an admin seeded by the database owner; no public first-call bootstrap. +export const setResendConfig = spacetimedb.procedure( + { + apiKey: t.string(), + webhookSigningSecret: t.option(t.string()), + defaultFrom: t.option(t.string()), + }, + t.unit(), + (ctx, args) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + ctx.withTx(tx => { + upsertConfig(tx, args); + }); + return {}; + } +); + +export const getResendConfigStatus = spacetimedb.procedure( + {}, + t.object('ResendConfigStatus', { + isConfigured: t.bool(), + hasWebhookSecret: t.bool(), + defaultFrom: t.option(t.string()), + apiKeyLength: t.u16(), + }), + ctx => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + return ctx.withTx(tx => { + const row = tx.db.resendConfig.singleton.find(true); + if (!row) { + return { + isConfigured: false, + hasWebhookSecret: false, + defaultFrom: undefined, + apiKeyLength: 0, + }; + } + return { + isConfigured: true, + hasWebhookSecret: row.webhookSigningSecret !== undefined, + defaultFrom: row.defaultFrom, + apiKeyLength: row.apiKey.length, + }; + }); + } +); diff --git a/spacetime-resend-ts/src/submodule/email-input.ts b/spacetime-resend-ts/src/submodule/email-input.ts new file mode 100644 index 00000000000..1b52a077e12 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/email-input.ts @@ -0,0 +1,106 @@ +import { errors } from './errors.js'; +import { hasControlCharacter } from './text-validation.js'; + +export type EmailInput = { + from?: string | undefined; + to: string[]; + subject: string; + html?: string | undefined; + text?: string | undefined; + cc?: string[] | undefined; + bcc?: string[] | undefined; + replyTo?: string[] | undefined; + tagsJson?: string | undefined; + headersJson?: string | undefined; + scheduledAt?: string | undefined; +}; + +function fail(code: string): never { + throw new Error(code); +} + +function validateAddressList( + values: string[] | undefined, + tooMany: string, + invalidAddress: string +): void { + if (values === undefined) return; + if (values.length > 100) fail(tooMany); + for (const value of values) { + if ( + value.length === 0 || + value.length > 320 || + hasControlCharacter(value) + ) { + fail(invalidAddress); + } + } +} + +function validateJson( + value: string | undefined, + tooLarge: string, + invalidJson: string, + maxLength: number +): void { + if (value === undefined) return; + if (value.length > maxLength) fail(tooLarge); + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + fail(invalidJson); + } + if (parsed === null || typeof parsed !== 'object') fail(invalidJson); +} + +export function validateEmailInput(args: EmailInput): void { + if (args.to.length === 0) fail(errors.sendEmailNoRecipients); + validateAddressList(args.to, errors.toTooMany, errors.toInvalidAddress); + validateAddressList(args.cc, errors.ccTooMany, errors.ccInvalidAddress); + validateAddressList(args.bcc, errors.bccTooMany, errors.bccInvalidAddress); + validateAddressList( + args.replyTo, + errors.replyToTooMany, + errors.replyToInvalidAddress + ); + const recipientCount = + args.to.length + (args.cc?.length ?? 0) + (args.bcc?.length ?? 0); + if (recipientCount > 100) fail(errors.sendEmailTooManyRecipients); + if ( + args.from !== undefined && + (args.from.length === 0 || + args.from.length > 320 || + hasControlCharacter(args.from)) + ) + fail(errors.sendEmailInvalidFrom); + if ( + args.subject.length === 0 || + args.subject.length > 998 || + hasControlCharacter(args.subject) + ) { + fail(errors.sendEmailInvalidSubject); + } + if (args.html === undefined && args.text === undefined) + fail(errors.sendEmailMissingContent); + if ((args.html?.length ?? 0) > 200_000) fail(errors.sendEmailHtmlTooLarge); + if ((args.text?.length ?? 0) > 200_000) fail(errors.sendEmailTextTooLarge); + validateJson( + args.tagsJson, + errors.tagsTooLarge, + errors.tagsInvalidJson, + 16_384 + ); + validateJson( + args.headersJson, + errors.headersTooLarge, + errors.headersInvalidJson, + 16_384 + ); + if ( + (args.scheduledAt?.length ?? 0) > 128 || + hasControlCharacter(args.scheduledAt ?? '') + ) { + fail(errors.sendEmailInvalidSchedule); + } +} diff --git a/spacetime-resend-ts/src/submodule/email_writes.ts b/spacetime-resend-ts/src/submodule/email_writes.ts new file mode 100644 index 00000000000..1519cb7b101 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/email_writes.ts @@ -0,0 +1,99 @@ +import { + EmailStatus, + type EmailStatusValue, + type ModuleTimestamp, + type WriteCtx, +} from './schema.js'; + +const STATUS_ORDER = { + Queued: 0, + Sent: 1, + DeliveryDelayed: 2, + Delivered: 3, + Cancelled: 4, + Failed: 5, + Bounced: 6, +}; + +// Any field passed as `undefined` preserves the existing row's value. Used by webhooks (sparse per-event fields). +export function upsertEmail( + ctx: WriteCtx, + now: ModuleTimestamp, + args: { + resendId: string; + fromAddress: string; + toAddressesJson: string; + subject: string | undefined; + html: string | undefined; + text: string | undefined; + status: EmailStatusValue | undefined; + statusUpdatedAt?: ModuleTimestamp; + lastError: string | undefined; + bouncedAt: ModuleTimestamp | undefined; + bounceJson: string | undefined; + failedAt: ModuleTimestamp | undefined; + failureReason: string | undefined; + complained: boolean; + complainedAt: ModuleTimestamp | undefined; + opened: boolean; + openedAt: ModuleTimestamp | undefined; + clicked: boolean; + clickedAt: ModuleTimestamp | undefined; + deliveredAt: ModuleTimestamp | undefined; + sentAt: ModuleTimestamp | undefined; + tagsJson: string | undefined; + userId: string | undefined; + orgId: string | undefined; + } +) { + const existing = ctx.db.resendEmail.resendId.find(args.resendId); + const statusTime = args.statusUpdatedAt ?? now; + // Late webhooks and send responses cannot undo a later delivery stage. + const replaceStatus = + args.status !== undefined && + (!existing || + (STATUS_ORDER[args.status.tag] >= STATUS_ORDER[existing.status.tag] && + (existing.status.tag === 'Queued' || + !existing.statusUpdatedAt || + statusTime.microsSinceUnixEpoch >= + existing.statusUpdatedAt.microsSinceUnixEpoch))); + // Error and bounce details describe the status that produced them. + const statusDetail = replaceStatus ? args : undefined; + const row = { + resendId: args.resendId, + fromAddress: args.fromAddress, + toAddressesJson: args.toAddressesJson, + subject: args.subject ?? existing?.subject, + html: args.html ?? existing?.html, + text: args.text ?? existing?.text, + status: + replaceStatus && args.status + ? args.status + : (existing?.status ?? EmailStatus.Queued), + statusUpdatedAt: replaceStatus ? statusTime : existing?.statusUpdatedAt, + lastError: statusDetail?.lastError ?? existing?.lastError, + bouncedAt: statusDetail?.bouncedAt ?? existing?.bouncedAt, + bounceJson: statusDetail?.bounceJson ?? existing?.bounceJson, + failedAt: statusDetail?.failedAt ?? existing?.failedAt, + failureReason: statusDetail?.failureReason ?? existing?.failureReason, + complained: args.complained || (existing?.complained ?? false), + complainedAt: args.complainedAt ?? existing?.complainedAt, + opened: args.opened || (existing?.opened ?? false), + openedAt: args.openedAt ?? existing?.openedAt, + clicked: args.clicked || (existing?.clicked ?? false), + clickedAt: args.clickedAt ?? existing?.clickedAt, + deliveredAt: args.deliveredAt ?? existing?.deliveredAt, + sentAt: args.sentAt ?? existing?.sentAt, + tagsJson: args.tagsJson ?? existing?.tagsJson, + userId: args.userId ?? existing?.userId, + orgId: args.orgId ?? existing?.orgId, + createdAt: existing?.createdAt ?? now, + updatedAt: now, + }; + + if (!existing) { + ctx.db.resendEmail.insert(row); + return; + } + ctx.db.resendEmail.resendId.update(row); +} diff --git a/spacetime-resend-ts/src/submodule/errors.ts b/spacetime-resend-ts/src/submodule/errors.ts new file mode 100644 index 00000000000..20afc973521 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/errors.ts @@ -0,0 +1,44 @@ +export const errors = { + notAuthorized: 'resend.not_authorized', + cannotRemoveLastAdmin: 'resend.cannot_remove_last_admin', + configNotSet: 'resend.config_not_set', + requestInvalid: 'resend.request_invalid', + requestPathInvalid: 'resend.request_path_invalid', + requestMethodInvalid: 'resend.request_method_invalid', + requestBodyTooLarge: 'resend.request_body_too_large', + idempotencyKeyTooLong: 'resend.idempotency_key_too_long', + sendEmailInvalidInput: 'resend.send_email_invalid_input', + sendEmailNoRecipients: 'resend.send_email_no_recipients', + sendEmailTooManyRecipients: 'resend.send_email_too_many_recipients', + sendEmailInvalidFrom: 'resend.send_email_invalid_from', + sendEmailInvalidSubject: 'resend.send_email_invalid_subject', + sendEmailMissingContent: 'resend.send_email_missing_content', + sendEmailHtmlTooLarge: 'resend.send_email_html_too_large', + sendEmailTextTooLarge: 'resend.send_email_text_too_large', + sendEmailInvalidSchedule: 'resend.send_email_invalid_schedule', + sendEmailMissingFrom: 'resend.send_email_missing_from', + sendEmailFailed: 'resend.send_email_failed', + sendEmailInvalidResponse: 'resend.send_email_invalid_response', + toTooMany: 'resend.to_too_many', + toInvalidAddress: 'resend.to_invalid_address', + ccTooMany: 'resend.cc_too_many', + ccInvalidAddress: 'resend.cc_invalid_address', + bccTooMany: 'resend.bcc_too_many', + bccInvalidAddress: 'resend.bcc_invalid_address', + replyToTooMany: 'resend.reply_to_too_many', + replyToInvalidAddress: 'resend.reply_to_invalid_address', + tagsTooLarge: 'resend.tags_too_large', + tagsInvalidJson: 'resend.tags_invalid_json', + headersTooLarge: 'resend.headers_too_large', + headersInvalidJson: 'resend.headers_invalid_json', + cancelEmailFailed: 'resend.cancel_email_failed', + webhookMethodNotAllowed: 'resend.webhook_method_not_allowed', + webhookMetadataInvalid: 'resend.webhook_metadata_invalid', + webhookMetadataMismatch: 'resend.webhook_metadata_mismatch', + webhookPayloadTooLarge: 'resend.webhook_payload_too_large', + webhookHeaderTooLarge: 'resend.webhook_header_too_large', + webhookSecretNotConfigured: 'resend.webhook_secret_not_configured', + webhookSignatureMismatch: 'resend.webhook_signature_mismatch', + webhookPayloadInvalid: 'resend.webhook_payload_invalid', + webhookEventNotFound: 'resend.webhook_event_not_found', +} as const; diff --git a/spacetime-resend-ts/src/submodule/http.ts b/spacetime-resend-ts/src/submodule/http.ts new file mode 100644 index 00000000000..fc924a1184d --- /dev/null +++ b/spacetime-resend-ts/src/submodule/http.ts @@ -0,0 +1,68 @@ +import * as v from 'valibot'; +import { type ProcedureModuleCtx, vResendErrorBody } from './schema.js'; +import { safeJsonParse, throwSenderError } from './validation.js'; +import { buildResendHttpRequest } from './request.js'; +import { errors } from './errors.js'; + +export type ResendHttpResponse = { + status: number; + body: string; +}; + +export function callResend( + ctx: ProcedureModuleCtx, + args: { + method: string; + path: string; + apiKey: string; + jsonBody: string | undefined; + idempotencyKey: string | undefined; + } +): ResendHttpResponse { + let request; + try { + request = buildResendHttpRequest(args); + } catch (error) { + throwSenderError( + error instanceof Error ? error.message : errors.requestInvalid + ); + } + const response = ctx.http.fetch(request.url, { + method: request.method, + headers: request.headers, + body: request.body, + }); + return { + status: response.status, + body: response.text(), + }; +} +export function ensureOkOrThrow( + response: ResendHttpResponse, + errorPrefix: string +): void { + if (response.status >= 200 && response.status < 300) return; + throwSenderError( + `${errorPrefix}:${response.status}${resendErrorSuffix(response.body)}` + ); +} + +export function resendErrorSuffix(body: string): string { + const parsed = safeJsonParse(body); + if (parsed !== undefined) { + const result = v.safeParse(vResendErrorBody, parsed); + if (result.success) { + const parts: string[] = []; + if (result.output.name) parts.push(`name=${result.output.name}`); + if (result.output.message) { + parts.push( + `msg=${result.output.message.replace(/\s+/g, ' ').slice(0, 240)}` + ); + } + if (parts.length > 0) return `:${parts.join('|')}`; + } + } + const compact = body.replace(/\s+/g, ' ').trim(); + if (!compact) return ''; + return `:body=${compact.slice(0, 240)}`; +} diff --git a/spacetime-resend-ts/src/submodule/install.ts b/spacetime-resend-ts/src/submodule/install.ts new file mode 100644 index 00000000000..493ec8558cf --- /dev/null +++ b/spacetime-resend-ts/src/submodule/install.ts @@ -0,0 +1,9 @@ +import type { ReducerModuleCtx } from './schema.js'; + +export function install(ctx: ReducerModuleCtx) { + if (ctx.db.resendAdminIdentity.identity.find(ctx.sender) != null) return; + ctx.db.resendAdminIdentity.insert({ + identity: ctx.sender, + addedAt: ctx.timestamp, + }); +} diff --git a/spacetime-resend-ts/src/submodule/operations.ts b/spacetime-resend-ts/src/submodule/operations.ts new file mode 100644 index 00000000000..e5ba032dc11 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/operations.ts @@ -0,0 +1,370 @@ +import * as v from 'valibot'; +import { + EmailStatus, + emailStatus, + resendDeliveryEventTable, + resendEmailTable, + resendWebhookEventTable, + sendEmailResult, + spacetimedb, + t, + vSendEmailResponse, + type ProcedureModuleCtx, + type WriteCtx, +} from './schema.js'; +import { callResend, ensureOkOrThrow } from './http.js'; +import { + safeJsonParse, + summarizeIssues, + throwSenderError, +} from './validation.js'; +import { upsertEmail } from './email_writes.js'; +import { loadConfigOrThrowFromProcedure } from './config.js'; +import { adminVerdict, denyIfNotAdmin } from './auth.js'; +import { validateEmailInput } from './email-input.js'; +import { errors } from './errors.js'; + +function requireProcedureAdmin(ctx: ProcedureModuleCtx): void { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); +} + +const MAX_QUERY_ROWS = 1000; + +function takeRows(rows: Iterable): T[] { + const out: T[] = []; + for (const row of rows) { + if (out.length >= MAX_QUERY_ROWS) break; + out.push(row); + } + return out; +} + +// Resend's send API takes tags as `[{ name, value }]`. +const vSendTags = v.array(v.object({ name: v.string(), value: v.string() })); + +function extractTagFieldsFromJson(tagsJson: string | undefined): { + userId: string | undefined; + orgId: string | undefined; +} { + const result = v.safeParse(vSendTags, tagsJson && safeJsonParse(tagsJson)); + if (!result.success) return { userId: undefined, orgId: undefined }; + const tags = result.output; + return { + userId: tags.find(tag => tag.name === 'userId')?.value, + orgId: tags.find(tag => tag.name === 'orgId')?.value, + }; +} + +// Resend expects snake_case fields in the POST /emails request body. +type ResendSendEmailBody = { + from: string; + to: string[]; + subject: string; + html?: string; + text?: string; + cc?: string[]; + bcc?: string[]; + reply_to?: string[]; + scheduled_at?: string; + tags?: unknown; + headers?: unknown; +}; + +function buildSendEmailBody(args: { + from: string; + to: string[]; + subject: string; + html: string | undefined; + text: string | undefined; + cc: string[] | undefined; + bcc: string[] | undefined; + replyTo: string[] | undefined; + tagsJson: string | undefined; + headersJson: string | undefined; + scheduledAt: string | undefined; +}): string { + const body: ResendSendEmailBody = { + from: args.from, + to: args.to, + subject: args.subject, + }; + if (args.html !== undefined) body.html = args.html; + if (args.text !== undefined) body.text = args.text; + if (args.cc !== undefined && args.cc.length > 0) body.cc = args.cc; + if (args.bcc !== undefined && args.bcc.length > 0) body.bcc = args.bcc; + if (args.replyTo !== undefined && args.replyTo.length > 0) { + body.reply_to = args.replyTo; + } + if (args.scheduledAt !== undefined) body.scheduled_at = args.scheduledAt; + if (args.tagsJson !== undefined) { + const parsed = safeJsonParse(args.tagsJson); + if (parsed !== undefined) body.tags = parsed; + } + if (args.headersJson !== undefined) { + const parsed = safeJsonParse(args.headersJson); + if (parsed !== undefined) body.headers = parsed; + } + return JSON.stringify(body); +} + +function recordQueuedEmail( + ctx: WriteCtx, + now: ProcedureModuleCtx['timestamp'], + args: { + resendId: string; + from: string; + to: string[]; + subject: string; + html: string | undefined; + text: string | undefined; + tagsJson: string | undefined; + } +) { + const tagFields = extractTagFieldsFromJson(args.tagsJson); + upsertEmail(ctx, now, { + resendId: args.resendId, + fromAddress: args.from, + toAddressesJson: JSON.stringify(args.to), + subject: args.subject, + html: args.html, + text: args.text, + status: EmailStatus.Queued, + lastError: undefined, + bouncedAt: undefined, + bounceJson: undefined, + failedAt: undefined, + failureReason: undefined, + complained: false, + complainedAt: undefined, + opened: false, + openedAt: undefined, + clicked: false, + clickedAt: undefined, + deliveredAt: undefined, + sentAt: undefined, + tagsJson: args.tagsJson, + userId: tagFields.userId, + orgId: tagFields.orgId, + }); +} + +export type SendEmailArgs = { + from?: string | undefined; + to: string[]; + subject: string; + html?: string | undefined; + text?: string | undefined; + cc?: string[] | undefined; + bcc?: string[] | undefined; + replyTo?: string[] | undefined; + tagsJson?: string | undefined; + headersJson?: string | undefined; + scheduledAt?: string | undefined; + idempotencyKey?: string | undefined; +}; + +export function sendEmailRequest(ctx: ProcedureModuleCtx, args: SendEmailArgs) { + try { + validateEmailInput(args); + } catch (error) { + throwSenderError( + error instanceof Error ? error.message : errors.sendEmailInvalidInput + ); + } + const cfg = loadConfigOrThrowFromProcedure(ctx); + const fromAddress = args.from ?? cfg.defaultFrom; + if (!fromAddress) throwSenderError(errors.sendEmailMissingFrom); + + const jsonBody = buildSendEmailBody({ + from: fromAddress, + to: args.to, + subject: args.subject, + html: args.html, + text: args.text, + cc: args.cc, + bcc: args.bcc, + replyTo: args.replyTo, + tagsJson: args.tagsJson, + headersJson: args.headersJson, + scheduledAt: args.scheduledAt, + }); + + const response = callResend(ctx, { + method: 'POST', + path: '/emails', + apiKey: cfg.apiKey, + jsonBody, + idempotencyKey: args.idempotencyKey, + }); + ensureOkOrThrow(response, errors.sendEmailFailed); + + const parsed = safeJsonParse(response.body); + if (parsed === undefined) throwSenderError(errors.sendEmailInvalidResponse); + const result = v.safeParse(vSendEmailResponse, parsed); + if (!result.success) { + throwSenderError( + `${errors.sendEmailInvalidResponse}:${summarizeIssues(result.issues)}` + ); + } + + const resendId = result.output.id; + ctx.withTx(tx => { + recordQueuedEmail(tx, ctx.timestamp, { + resendId, + from: fromAddress, + to: args.to, + subject: args.subject, + html: args.html, + text: args.text, + tagsJson: args.tagsJson, + }); + }); + return { resendId }; +} + +const sendEmailArgs = { + from: t.option(t.string()), + to: t.array(t.string()), + subject: t.string(), + html: t.option(t.string()), + text: t.option(t.string()), + cc: t.option(t.array(t.string())), + bcc: t.option(t.array(t.string())), + replyTo: t.option(t.array(t.string())), + tagsJson: t.option(t.string()), + headersJson: t.option(t.string()), + scheduledAt: t.option(t.string()), + idempotencyKey: t.option(t.string()), +}; + +export const sendEmail = spacetimedb.procedure( + sendEmailArgs, + sendEmailResult, + (ctx, args) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + return sendEmailRequest(ctx, args); + } +); + +export const cancelEmail = spacetimedb.procedure( + { resendId: t.string() }, + t.unit(), + (ctx, args) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + const cfg = loadConfigOrThrowFromProcedure(ctx); + const response = callResend(ctx, { + method: 'POST', + path: `/emails/${args.resendId}/cancel`, + apiKey: cfg.apiKey, + jsonBody: undefined, + idempotencyKey: undefined, + }); + ensureOkOrThrow(response, errors.cancelEmailFailed); + + ctx.withTx(tx => { + const existing = tx.db.resendEmail.resendId.find(args.resendId); + if (!existing) return; + const updated = { + ...existing, + status: EmailStatus.Cancelled, + statusUpdatedAt: ctx.timestamp, + updatedAt: ctx.timestamp, + }; + tx.db.resendEmail.resendId.update(updated); + }); + return {}; + } +); + +export const getEmail = spacetimedb.procedure( + { resendId: t.string() }, + t.option(resendEmailTable.rowType), + (ctx, { resendId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx( + tx => tx.db.resendEmail.resendId.find(resendId) ?? undefined + ); + } +); + +export const getWebhookEvent = spacetimedb.procedure( + { eventId: t.string() }, + t.option(resendWebhookEventTable.rowType), + (ctx, { eventId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx( + tx => tx.db.resendWebhookEvent.eventId.find(eventId) ?? undefined + ); + } +); + +export const listEmailsByUserId = spacetimedb.procedure( + { userId: t.string() }, + t.array(resendEmailTable.rowType), + (ctx, { userId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => + takeRows(tx.db.resendEmail.byUserId.filter(userId)) + ); + } +); + +export const listEmailsByOrgId = spacetimedb.procedure( + { orgId: t.string() }, + t.array(resendEmailTable.rowType), + (ctx, { orgId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => takeRows(tx.db.resendEmail.byOrgId.filter(orgId))); + } +); + +export const listEmailsByStatus = spacetimedb.procedure( + { status: emailStatus }, + t.array(resendEmailTable.rowType), + (ctx, { status }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => + takeRows(tx.db.resendEmail.byStatus.filter(status)) + ); + } +); + +export const listDeliveryEventsForEmail = spacetimedb.procedure( + { resendId: t.string() }, + t.array(resendDeliveryEventTable.rowType), + (ctx, { resendId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => + takeRows(tx.db.resendDeliveryEvent.byResendId.filter(resendId)) + ); + } +); + +export const resendApiRequest = spacetimedb.procedure( + { + method: t.string(), + path: t.string(), + jsonBody: t.option(t.string()), + idempotencyKey: t.option(t.string()), + }, + t.object('ResendApiRequestResult', { + status: t.u16(), + body: t.string(), + }), + (ctx, args) => { + // Administrators may make authenticated Resend calls with the stored key. + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + const cfg = loadConfigOrThrowFromProcedure(ctx); + return callResend(ctx, { + method: args.method, + path: args.path, + apiKey: cfg.apiKey, + jsonBody: args.jsonBody, + idempotencyKey: args.idempotencyKey, + }); + } +); diff --git a/spacetime-resend-ts/src/submodule/request.ts b/spacetime-resend-ts/src/submodule/request.ts new file mode 100644 index 00000000000..bbf13cec563 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/request.ts @@ -0,0 +1,68 @@ +import { errors } from './errors.js'; +import { hasControlCharacter } from './text-validation.js'; + +const RESEND_API_BASE = 'https://api.resend.com'; +const ALLOWED_METHODS = new Set(['GET', 'POST', 'PATCH', 'DELETE']); +const MAX_PATH_LENGTH = 2048; +const MAX_JSON_BODY_LENGTH = 256 * 1024; +const MAX_IDEMPOTENCY_KEY_LENGTH = 256; + +export type ResendHttpRequest = { + method: string; + url: string; + headers: Record; + body: string | undefined; +}; + +function validatePath(path: string): string { + const normalized = path.trim(); + if (!normalized.startsWith('/') || normalized.startsWith('//')) { + throw new Error(errors.requestPathInvalid); + } + if (normalized.includes('\\') || normalized.includes('#')) { + throw new Error(errors.requestPathInvalid); + } + if (normalized.length > MAX_PATH_LENGTH || hasControlCharacter(normalized)) { + throw new Error(errors.requestPathInvalid); + } + return normalized; +} + +export function buildResendHttpRequest(args: { + method: string; + path: string; + apiKey: string; + jsonBody: string | undefined; + idempotencyKey: string | undefined; +}): ResendHttpRequest { + const method = args.method.trim().toUpperCase(); + if (!ALLOWED_METHODS.has(method)) { + throw new Error(errors.requestMethodInvalid); + } + + const path = validatePath(args.path); + const body = args.jsonBody?.length ? args.jsonBody : undefined; + if (body !== undefined && body.length > MAX_JSON_BODY_LENGTH) { + throw new Error(errors.requestBodyTooLarge); + } + if ( + args.idempotencyKey && + args.idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH + ) { + throw new Error(errors.idempotencyKeyTooLong); + } + + const headers: Record = { + Authorization: `Bearer ${args.apiKey}`, + Accept: 'application/json', + }; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + if (args.idempotencyKey) headers['Idempotency-Key'] = args.idempotencyKey; + + return { + method, + url: `${RESEND_API_BASE}${path}`, + headers, + body, + }; +} diff --git a/spacetime-resend-ts/src/submodule/schema.ts b/spacetime-resend-ts/src/submodule/schema.ts new file mode 100644 index 00000000000..44083445f4f --- /dev/null +++ b/spacetime-resend-ts/src/submodule/schema.ts @@ -0,0 +1,283 @@ +import { + schema, + table, + t, + Range, + SenderError, + type ProcedureCtx, + type ReducerCtx, + type TransactionCtx, +} from 'spacetimedb/server'; +import * as v from 'valibot'; +import { install } from './install.js'; + +// Webhook delivery state. Received = ingest accepted. Processed = applied. +// Ignored = event type this submodule does not handle. Failed = invalid payload. +export const webhookEventStatus = t.enum('WebhookEventStatus', [ + 'Received', + 'Processed', + 'Ignored', + 'Failed', +]); +export const WebhookEventStatus = { + Received: { tag: 'Received' as const }, + Processed: { tag: 'Processed' as const }, + Ignored: { tag: 'Ignored' as const }, + Failed: { tag: 'Failed' as const }, +}; + +// Lifecycle of a tracked outbound email. Tags match Resend's +// `email.` webhook events for direct ingestion mapping. +export const emailStatus = t.enum('EmailStatus', [ + 'Queued', + 'Sent', + 'Delivered', + 'DeliveryDelayed', + 'Bounced', + 'Failed', + 'Cancelled', +]); +export const EmailStatus = { + Queued: { tag: 'Queued' as const }, + Sent: { tag: 'Sent' as const }, + Delivered: { tag: 'Delivered' as const }, + DeliveryDelayed: { tag: 'DeliveryDelayed' as const }, + Bounced: { tag: 'Bounced' as const }, + Failed: { tag: 'Failed' as const }, + Cancelled: { tag: 'Cancelled' as const }, +}; +export type EmailStatusValue = (typeof EmailStatus)[keyof typeof EmailStatus]; +export type WebhookEventStatusValue = + (typeof WebhookEventStatus)[keyof typeof WebhookEventStatus]; + +export const resendEmailRow = { + resendId: t.string().primaryKey(), + fromAddress: t.string(), + toAddressesJson: t.string(), + subject: t.option(t.string()), + status: emailStatus, + lastError: t.option(t.string()), + bouncedAt: t.option(t.timestamp()), + bounceJson: t.option(t.string()), + failedAt: t.option(t.timestamp()), + failureReason: t.option(t.string()), + complained: t.bool(), + complainedAt: t.option(t.timestamp()), + opened: t.bool(), + openedAt: t.option(t.timestamp()), + clicked: t.bool(), + clickedAt: t.option(t.timestamp()), + deliveredAt: t.option(t.timestamp()), + sentAt: t.option(t.timestamp()), + html: t.option(t.string()), + text: t.option(t.string()), + tagsJson: t.option(t.string()), + userId: t.option(t.string()), + orgId: t.option(t.string()), + createdAt: t.timestamp(), + updatedAt: t.timestamp(), + statusUpdatedAt: t.option(t.timestamp()), +}; + +export const resendDeliveryEventRow = { + eventId: t.string().primaryKey(), + resendId: t.string(), + eventType: t.string(), + createdAtIso: t.string(), + detailJson: t.option(t.string()), + insertedAt: t.timestamp(), +}; + +export const resendWebhookEventRow = { + eventId: t.string().primaryKey(), + eventType: t.string(), + payloadJson: t.string(), + signatureHeader: t.option(t.string()), + timestampHeader: t.option(t.string()), + status: webhookEventStatus, + errorMessage: t.option(t.string()), + receivedAt: t.timestamp(), + processedAt: t.option(t.timestamp()), +}; + +// Private singleton; secrets never leak via subscription. +export const resendConfigRow = { + singleton: t.bool().primaryKey(), + apiKey: t.string(), + webhookSigningSecret: t.option(t.string()), + defaultFrom: t.option(t.string()), + updatedAt: t.timestamp(), +}; + +// Fresh publishes seed the owner via init; public procedures never bootstrap admin state. +export const resendAdminIdentityRow = { + identity: t.identity().primaryKey(), + addedAt: t.timestamp(), +}; + +export const resendEmailTable = table( + { + name: 'resend_email', + public: false, + indexes: [ + { accessor: 'byUserId', algorithm: 'btree', columns: ['userId'] }, + { accessor: 'byOrgId', algorithm: 'btree', columns: ['orgId'] }, + { accessor: 'byStatus', algorithm: 'btree', columns: ['status'] }, + ], + }, + resendEmailRow +); + +export const resendDeliveryEventTable = table( + { + name: 'resend_delivery_event', + public: false, + indexes: [ + { accessor: 'byResendId', algorithm: 'btree', columns: ['resendId'] }, + ], + }, + resendDeliveryEventRow +); + +// Private because the raw payload and signature headers are operational data. +// Host modules can expose an admin-only view when needed. +export const resendWebhookEventTable = table( + { + name: 'resend_webhook_event', + public: false, + indexes: [ + { accessor: 'byStatus', algorithm: 'btree', columns: ['status'] }, + ], + }, + resendWebhookEventRow +); + +export const resendConfigTable = table( + { name: 'resend_config', public: false, indexes: [] }, + resendConfigRow +); + +export const resendAdminIdentityTable = table( + { name: 'resend_admin_identity', public: false, indexes: [] }, + resendAdminIdentityRow +); + +export const spacetimedb = schema({ + resendEmail: resendEmailTable, + resendDeliveryEvent: resendDeliveryEventTable, + resendWebhookEvent: resendWebhookEventTable, + resendConfig: resendConfigTable, + resendAdminIdentity: resendAdminIdentityTable, +}); + +export const init = spacetimedb.init(ctx => { + install(ctx); +}); + +export default spacetimedb; + +export type ReducerModuleCtx = ReducerCtx; +export type ProcedureModuleCtx = ProcedureCtx; +export type TransactionModuleCtx = TransactionCtx< + typeof spacetimedb.schemaType +>; +export type WriteCtx = ReducerModuleCtx | TransactionModuleCtx; +export type ModuleTimestamp = ReducerModuleCtx['timestamp']; + +export const sendEmailResult = t.object('SendEmailResult', { + resendId: t.string(), +}); + +export { Range, SenderError, t }; + +// Mirror Resend SDK's BaseEmailEventData. +const vBaseEmailEventData = { + broadcast_id: v.optional(v.string()), + created_at: v.string(), + email_id: v.string(), + from: v.string(), + to: v.array(v.string()), + subject: v.string(), + template_id: v.optional(v.string()), + tags: v.optional(v.record(v.string(), v.string())), +}; + +const vBaseEvent = { + created_at: v.string(), +}; + +export const vEmailEvent = v.variant('type', [ + v.object({ + ...vBaseEvent, + type: v.literal('email.sent'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.delivered'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.delivery_delayed'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.complained'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.bounced'), + data: v.object({ + ...vBaseEmailEventData, + bounce: v.object({ + message: v.string(), + subType: v.string(), + type: v.string(), + }), + }), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.opened'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.clicked'), + data: v.object({ + ...vBaseEmailEventData, + click: v.object({ + ipAddress: v.string(), + link: v.string(), + timestamp: v.string(), + userAgent: v.string(), + }), + }), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.failed'), + data: v.object({ + ...vBaseEmailEventData, + failed: v.object({ + reason: v.string(), + }), + }), + }), +]); + +export type EmailEvent = v.InferOutput; +export type EmailEventType = EmailEvent['type']; + +export const vResendErrorBody = v.object({ + name: v.optional(v.string()), + message: v.optional(v.string()), + statusCode: v.optional(v.union([v.number(), v.null()])), +}); + +export const vSendEmailResponse = v.object({ + id: v.string(), +}); diff --git a/spacetime-resend-ts/src/submodule/text-validation.ts b/spacetime-resend-ts/src/submodule/text-validation.ts new file mode 100644 index 00000000000..5409d6119b8 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/text-validation.ts @@ -0,0 +1,7 @@ +export function hasControlCharacter(value: string): boolean { + for (let index = 0; index < value.length; index++) { + const code = value.charCodeAt(index); + if (code <= 0x1f || code === 0x7f) return true; + } + return false; +} diff --git a/spacetime-resend-ts/src/submodule/validation.ts b/spacetime-resend-ts/src/submodule/validation.ts new file mode 100644 index 00000000000..181f0f5e9ad --- /dev/null +++ b/spacetime-resend-ts/src/submodule/validation.ts @@ -0,0 +1,32 @@ +import * as v from 'valibot'; +import { SenderError } from 'spacetimedb/server'; + +export function assertExhaustive(value: never): never { + throw new Error(`Unhandled discriminant: ${value as string}`); +} + +export function throwSenderError(message: string): never { + throw new SenderError(message); +} + +export function safeJsonParse(input: string): unknown { + try { + return JSON.parse(input); + } catch { + return undefined; + } +} + +export function summarizeIssues(issues: v.BaseIssue[]): string { + if (issues.length === 0) return 'no issues'; + const head = issues[0]!; + const path = (head.path ?? []) + .map(p => + typeof p.key === 'string' || typeof p.key === 'number' + ? String(p.key) + : '?' + ) + .join('.'); + const where = path ? ` at ${path}` : ''; + return `${head.message}${where}`; +} diff --git a/spacetime-resend-ts/src/submodule/webhook-metadata.ts b/spacetime-resend-ts/src/submodule/webhook-metadata.ts new file mode 100644 index 00000000000..62b77b6e133 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/webhook-metadata.ts @@ -0,0 +1,13 @@ +export function parseResendEventType(payloadJson: string): string | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(payloadJson); + } catch { + return undefined; + } + if (typeof parsed !== 'object' || parsed === null) return undefined; + const eventType = (parsed as Record).type; + return typeof eventType === 'string' && eventType.length > 0 + ? eventType + : undefined; +} diff --git a/spacetime-resend-ts/src/submodule/webhooks.ts b/spacetime-resend-ts/src/submodule/webhooks.ts new file mode 100644 index 00000000000..b249d22d20d --- /dev/null +++ b/spacetime-resend-ts/src/submodule/webhooks.ts @@ -0,0 +1,402 @@ +import * as v from 'valibot'; +import { Timestamp } from 'spacetimedb'; +import { + EmailStatus, + WebhookEventStatus, + spacetimedb, + t, + vEmailEvent, + type EmailEvent, + type EmailStatusValue, + type ModuleTimestamp, + type ReducerModuleCtx, + type WebhookEventStatusValue, + type WriteCtx, +} from './schema.js'; +import { upsertEmail } from './email_writes.js'; +import { requireAdmin } from './auth.js'; +import { verifySvixSignature } from '@spacetimedb/crypto'; +import { + SyncResponse, + type Request, + type HandlerContext, +} from 'spacetimedb/server'; +import { + assertExhaustive, + safeJsonParse, + summarizeIssues, + throwSenderError, +} from './validation.js'; +import { parseResendEventType } from './webhook-metadata.js'; +import { errors } from './errors.js'; + +type ResendTags = EmailEvent['data']['tags']; + +function tagsToJson(tags: ResendTags): string | undefined { + if (!tags) return undefined; + try { + return JSON.stringify(tags); + } catch { + return undefined; + } +} + +function extractTagFields(tags: ResendTags): { + userId: string | undefined; + orgId: string | undefined; +} { + if (!tags) return { userId: undefined, orgId: undefined }; + return { userId: tags['userId'], orgId: tags['orgId'] }; +} + +function recordDeliveryEvent( + ctx: WriteCtx, + now: ModuleTimestamp, + args: { + eventId: string; + resendId: string; + eventType: string; + createdAtIso: string; + detailJson: string | undefined; + } +) { + if (ctx.db.resendDeliveryEvent.eventId.find(args.eventId)) return; + ctx.db.resendDeliveryEvent.insert({ + eventId: args.eventId, + resendId: args.resendId, + eventType: args.eventType, + createdAtIso: args.createdAtIso, + detailJson: args.detailJson, + insertedAt: now, + }); +} + +function updateWebhookStatus( + ctx: ReducerModuleCtx, + eventId: string, + status: WebhookEventStatusValue, + errorMessage: string | undefined +) { + const existing = ctx.db.resendWebhookEvent.eventId.find(eventId); + if (!existing) return; + + const isTerminal = status.tag !== 'Received'; + const updated = { + ...existing, + status, + errorMessage, + processedAt: isTerminal ? ctx.timestamp : existing.processedAt, + }; + + ctx.db.resendWebhookEvent.eventId.update(updated); +} + +function makeEmailUpsertArgs( + event: EmailEvent, + now: ModuleTimestamp +): Parameters[2] { + const data = event.data; + const tagFields = extractTagFields(data.tags); + const tagsJson = tagsToJson(data.tags); + const subject = data.subject; + + const base = { + resendId: data.email_id, + fromAddress: data.from, + toAddressesJson: JSON.stringify(data.to), + subject, + // undefined preserves whatever send_email recorded. + html: undefined, + text: undefined, + lastError: undefined, + bouncedAt: undefined, + bounceJson: undefined, + failedAt: undefined, + failureReason: undefined, + complained: false, + complainedAt: undefined, + opened: false, + openedAt: undefined, + clicked: false, + clickedAt: undefined, + deliveredAt: undefined, + sentAt: undefined, + tagsJson, + userId: tagFields.userId, + orgId: tagFields.orgId, + // status undefined = preserve existing or default to queued; branches override. + status: undefined as EmailStatusValue | undefined, + } satisfies Parameters[2]; + + switch (event.type) { + case 'email.sent': + return { ...base, status: EmailStatus.Sent, sentAt: now }; + case 'email.delivered': + return { ...base, status: EmailStatus.Delivered, deliveredAt: now }; + case 'email.delivery_delayed': + return { ...base, status: EmailStatus.DeliveryDelayed }; + case 'email.bounced': + return { + ...base, + status: EmailStatus.Bounced, + bouncedAt: now, + bounceJson: JSON.stringify(event.data.bounce), + lastError: event.data.bounce.message, + }; + case 'email.failed': + return { + ...base, + status: EmailStatus.Failed, + failedAt: now, + failureReason: event.data.failed.reason, + lastError: event.data.failed.reason, + }; + case 'email.complained': + return { ...base, complained: true, complainedAt: now }; + case 'email.opened': + return { ...base, opened: true, openedAt: now }; + case 'email.clicked': + return { ...base, clicked: true, clickedAt: now }; + default: + return assertExhaustive(event); + } +} + +function detailJsonForEvent(event: EmailEvent): string | undefined { + switch (event.type) { + case 'email.bounced': + return JSON.stringify(event.data.bounce); + case 'email.failed': + return JSON.stringify(event.data.failed); + case 'email.clicked': + return JSON.stringify(event.data.click); + case 'email.sent': + case 'email.delivered': + case 'email.delivery_delayed': + case 'email.complained': + case 'email.opened': + return undefined; + default: + return assertExhaustive(event); + } +} + +// Resend also sends event types this submodule does not track, such as +// `contact.*`, `domain.*`, and `email.received`. Those are acknowledged as Ignored. +const vHandledEventType = v.object({ + type: v.picklist( + vEmailEvent.options.map(option => option.entries.type.literal) + ), +}); + +function applyResendEvent( + ctx: ReducerModuleCtx, + eventId: string, + payloadJson: string +): { status: WebhookEventStatusValue; error: string | undefined } { + const parsed = safeJsonParse(payloadJson); + if (parsed === undefined) { + return { status: WebhookEventStatus.Failed, error: 'invalid JSON payload' }; + } + + const result = v.safeParse(vEmailEvent, parsed); + if (!result.success) { + if (!v.is(vHandledEventType, parsed)) { + return { status: WebhookEventStatus.Ignored, error: undefined }; + } + return { + status: WebhookEventStatus.Failed, + error: `payload validation failed: ${summarizeIssues(result.issues)}`, + }; + } + + const event = result.output; + const now = ctx.timestamp; + const eventMillis = Date.parse(event.created_at); + if (!Number.isFinite(eventMillis)) { + return { + status: WebhookEventStatus.Failed, + error: 'invalid event timestamp', + }; + } + const eventTime = new Timestamp(BigInt(eventMillis) * 1000n); + upsertEmail(ctx, now, { + ...makeEmailUpsertArgs(event, eventTime), + statusUpdatedAt: eventTime, + }); + recordDeliveryEvent(ctx, now, { + eventId, + resendId: event.data.email_id, + eventType: event.type, + createdAtIso: event.created_at, + detailJson: detailJsonForEvent(event), + }); + return { status: WebhookEventStatus.Processed, error: undefined }; +} + +export interface ResendWebhookIngestArgs { + eventId: string; + eventType: string; + payloadJson: string; + signatureHeader?: string | undefined; + timestampHeader?: string | undefined; +} + +const MAX_WEBHOOK_BODY_LENGTH = 1024 * 1024; +const MAX_WEBHOOK_HEADER_LENGTH = 8192; +const MAX_WEBHOOK_METADATA_LENGTH = 255; + +type WebhookRejection = { status: number; code: string }; + +// The reducer and HTTP route verify, store, and apply events in one transaction. +// Returns a rejection when the request is refused before anything is written, +// otherwise the stored event status. +function applyResendWebhook( + ctx: WriteCtx, + args: Omit +): WebhookRejection | WebhookEventStatusValue { + if ( + args.eventId.length === 0 || + args.eventId.length > MAX_WEBHOOK_METADATA_LENGTH + ) { + return { status: 400, code: errors.webhookMetadataInvalid }; + } + if (args.payloadJson.length > MAX_WEBHOOK_BODY_LENGTH) { + return { status: 413, code: errors.webhookPayloadTooLarge }; + } + if ( + (args.signatureHeader?.length ?? 0) > MAX_WEBHOOK_HEADER_LENGTH || + (args.timestampHeader?.length ?? 0) > MAX_WEBHOOK_HEADER_LENGTH + ) { + return { status: 400, code: errors.webhookHeaderTooLarge }; + } + + const cfg = ctx.db.resendConfig.singleton.find(true); + if (!cfg?.webhookSigningSecret) { + return { status: 500, code: errors.webhookSecretNotConfigured }; + } + const nowSeconds = Number(ctx.timestamp.microsSinceUnixEpoch / 1_000_000n); + const signature = verifySvixSignature({ + svixId: args.eventId, + svixTimestamp: args.timestampHeader ?? '', + svixSignature: args.signatureHeader ?? '', + rawBody: args.payloadJson, + secret: cfg.webhookSigningSecret, + nowSeconds, + }); + if (!signature.ok) { + return { + status: 401, + code: `${errors.webhookSignatureMismatch}:${signature.reason}`, + }; + } + + const signedEventType = parseResendEventType(args.payloadJson); + if ( + !signedEventType || + signedEventType.length > MAX_WEBHOOK_METADATA_LENGTH + ) { + return { status: 400, code: errors.webhookPayloadInvalid }; + } + + const existing = ctx.db.resendWebhookEvent.eventId.find(args.eventId); + if ( + existing?.status.tag === 'Processed' || + existing?.status.tag === 'Ignored' + ) { + return existing.status; + } + + if (!existing) + ctx.db.resendWebhookEvent.insert({ + eventId: args.eventId, + eventType: signedEventType, + payloadJson: args.payloadJson, + signatureHeader: args.signatureHeader, + timestampHeader: args.timestampHeader, + status: WebhookEventStatus.Received, + errorMessage: undefined, + receivedAt: ctx.timestamp, + processedAt: undefined, + }); + + const outcome = applyResendEvent( + ctx as ReducerModuleCtx, + args.eventId, + existing?.payloadJson ?? args.payloadJson + ); + updateWebhookStatus( + ctx as ReducerModuleCtx, + args.eventId, + outcome.status, + outcome.error + ); + return outcome.status; +} + +export const ingestResendWebhook = spacetimedb.reducer( + { + eventId: t.string(), + eventType: t.string(), + payloadJson: t.string(), + signatureHeader: t.option(t.string()), + timestampHeader: t.option(t.string()), + }, + (ctx, { eventType, ...args }) => { + if (eventType !== parseResendEventType(args.payloadJson)) { + throwSenderError(errors.webhookMetadataMismatch); + } + // A Failed event row commits so it can be read and replayed. + const result = applyResendWebhook(ctx, args); + if ('code' in result) throwSenderError(result.code); + } +); + +function webhookJson(body: unknown, status: number): SyncResponse { + return new SyncResponse(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +// Native SpacetimeDB HTTP route handler. Host modules register it on a router so +// Resend can post directly to the database. +export function makeResendWebhookHandler() { + // The host passes the submodule-scoped context, so this handler remains schema-agnostic. + return function resendWebhook( + ctx: HandlerContext, + req: Request + ): SyncResponse { + if (req.method.toUpperCase() !== 'POST') { + return webhookJson( + { ok: false, code: errors.webhookMethodNotAllowed }, + 405 + ); + } + + const args = { + eventId: req.headers.get('svix-id') ?? '', + payloadJson: req.text(), + signatureHeader: req.headers.get('svix-signature') ?? undefined, + timestampHeader: req.headers.get('svix-timestamp') ?? undefined, + }; + const result = ctx.withTx(tx => applyResendWebhook(tx as WriteCtx, args)); + if ('code' in result) + return webhookJson({ ok: false, code: result.code }, result.status); + return result.tag === 'Failed' + ? webhookJson({ ok: false, code: errors.webhookPayloadInvalid }, 400) + : webhookJson({ ok: true, code: 'ok' }, 200); + }; +} + +export const replayWebhookEvent = spacetimedb.reducer( + { eventId: t.string() }, + (ctx, { eventId }) => { + // Administrators may run this operation over stored events. + requireAdmin(ctx, ctx.sender); + const event = ctx.db.resendWebhookEvent.eventId.find(eventId); + if (!event) throwSenderError(`${errors.webhookEventNotFound}:${eventId}`); + const outcome = applyResendEvent(ctx, eventId, event.payloadJson); + updateWebhookStatus(ctx, eventId, outcome.status, outcome.error); + } +); diff --git a/spacetime-resend-ts/tsconfig.build.json b/spacetime-resend-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-resend-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-resend-ts/tsconfig.json b/spacetime-resend-ts/tsconfig.json new file mode 100644 index 00000000000..d4766a1709a --- /dev/null +++ b/spacetime-resend-ts/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "emitDeclarationOnly": false, + "noEmit": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "noImplicitAny": true, + "moduleResolution": "Bundler", + "isolatedDeclarations": false, + "esModuleInterop": false, + "allowSyntheticDefaultImports": false, + "useDefineForClassFields": true, + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules", "dist/**/*"] +} From ddbc32f2bd68fb10a480bcd4f03be11afd142f9c Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 9 Oct 2026 11:21:37 -0400 Subject: [PATCH 32/32] Run TypeScript submodule CI through cargo --- .github/workflows/ci.yml | 22 +++++-------------- Cargo.lock | 9 ++++++++ Cargo.toml | 1 + .../commands/typescript-submodules/Cargo.toml | 9 ++++++++ .../typescript-submodules/src/main.rs | 22 +++++++++++++++++++ tools/ci/src/main.rs | 4 ++++ 6 files changed, 51 insertions(+), 16 deletions(-) create mode 100644 tools/ci/commands/typescript-submodules/Cargo.toml create mode 100644 tools/ci/commands/typescript-submodules/src/main.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d692747d359..8ba1104e5ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1742,8 +1742,10 @@ jobs: with: run_install: true - - name: Build TypeScript SDK - run: pnpm --dir crates/bindings-typescript run build + - name: Install Rust toolchain + uses: dsherret/rust-toolchain-file@v1 + - name: Set default rust toolchain + run: rustup default $(rustup show active-toolchain | cut -d' ' -f1) - *set-cargo-target-dir - *download-build-artifacts @@ -1751,17 +1753,5 @@ jobs: - *expose-spacetime-cli - - name: Check submodules - run: | - pnpm -r -F "./spacetime-*-ts/**" run lint - pnpm -r -F "./spacetime-*-ts/**" run typecheck - pnpm -r -F "./spacetime-*-ts/**" run test - - # Starts an isolated server on a free local port with a temporary data - # directory. `spacetime start` runs the extracted spacetimedb-standalone - # beside spacetimedb-cli. - - name: Run cron crash-recovery test - run: pnpm --dir spacetime-cron-ts run test:recovery - - - name: Build submodule packages and examples - run: pnpm -r -F "./spacetime-*-ts/**" run build + - name: Check TypeScript submodules + run: cargo ci typescript-submodules diff --git a/Cargo.lock b/Cargo.lock index 6a114150c4d..45063e99f17 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1113,6 +1113,15 @@ dependencies = [ "duct", ] +[[package]] +name = "ci-typescript-submodules" +version = "0.1.0" +dependencies = [ + "anyhow", + "ci-common", + "clap 4.5.50", +] + [[package]] name = "ci-typescript-test" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 3c50704c305..4cf3a3d95a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,6 +82,7 @@ members = [ "tools/ci/commands/publish-checks", "tools/ci/commands/run-spacetime", "tools/ci/commands/typescript-test", + "tools/ci/commands/typescript-submodules", "tools/ci/commands/version-upgrade-check", "tools/ci/commands/docs", "tools/ci/commands/codeowners-check", diff --git a/tools/ci/commands/typescript-submodules/Cargo.toml b/tools/ci/commands/typescript-submodules/Cargo.toml new file mode 100644 index 00000000000..26e94017113 --- /dev/null +++ b/tools/ci/commands/typescript-submodules/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "ci-typescript-submodules" +version = "0.1.0" +edition.workspace = true + +[dependencies] +anyhow.workspace = true +clap.workspace = true +ci-common = { path = "../../common" } diff --git a/tools/ci/commands/typescript-submodules/src/main.rs b/tools/ci/commands/typescript-submodules/src/main.rs new file mode 100644 index 00000000000..a562c3eb543 --- /dev/null +++ b/tools/ci/commands/typescript-submodules/src/main.rs @@ -0,0 +1,22 @@ +use anyhow::Result; +use ci_common::pnpm; +use clap::Parser; + +/// Checks TypeScript submodules and builds their packages and examples. +#[derive(Parser)] +struct Cli {} + +fn main() -> Result<()> { + Cli::parse(); + ci_common::ensure_repo_root()?; + + pnpm(["--dir", "crates/bindings-typescript", "run", "build"]).run()?; + for script in ["lint", "typecheck", "test"] { + pnpm(["-r", "-F", "./spacetime-*-ts/**", "run", script]).run()?; + } + + // The recovery test starts and stops its own server on a free local port. + pnpm(["--dir", "spacetime-cron-ts", "run", "test:recovery"]).run()?; + pnpm(["-r", "-F", "./spacetime-*-ts/**", "run", "build"]).run()?; + Ok(()) +} diff --git a/tools/ci/src/main.rs b/tools/ci/src/main.rs index d004ec9e86b..7a701e5f360 100644 --- a/tools/ci/src/main.rs +++ b/tools/ci/src/main.rs @@ -56,6 +56,10 @@ const COMMANDS: &[Command] = &[ path: &["typescript-test"], package: "ci-typescript-test", }, + Command { + path: &["typescript-submodules"], + package: "ci-typescript-submodules", + }, Command { path: &["version-upgrade-check"], package: "ci-version-upgrade-check",