@joiner-platform/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -2
- package/bundled-resources/poe-tile-templates/base/CLAUDE.md +72 -0
- package/bundled-resources/poe-tile-templates/base/README.md +7 -0
- package/bundled-resources/poe-tile-templates/base/_bunfig.toml +8 -0
- package/bundled-resources/poe-tile-templates/base/_gitignore +18 -0
- package/bundled-resources/poe-tile-templates/base/client.ts +12 -0
- package/bundled-resources/poe-tile-templates/base/package.json +36 -0
- package/bundled-resources/poe-tile-templates/base/playwright.config.ts +38 -0
- package/bundled-resources/poe-tile-templates/base/scripts/check-source.ts +148 -0
- package/bundled-resources/poe-tile-templates/base/scripts/dev.ts +19 -0
- package/bundled-resources/poe-tile-templates/base/scripts/doctor.sh +29 -0
- package/bundled-resources/poe-tile-templates/base/scripts/visual-check.ts +64 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/backend-config.ts +9 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/client-config.ts +8 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/data/items.ts +16 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/index.ts +10 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/remove-todo.ts +5 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/set-todo.ts +20 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/types.ts +5 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators.test.ts +138 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/schema.ts +40 -0
- package/bundled-resources/poe-tile-templates/base/tests/e2e.test.playwright.ts +92 -0
- package/bundled-resources/poe-tile-templates/base/tests/mobile-viewport.test.playwright.ts +111 -0
- package/bundled-resources/poe-tile-templates/base/tests/render-check.test.playwright.ts +128 -0
- package/bundled-resources/poe-tile-templates/base/tests/screenshot.test.playwright.ts +86 -0
- package/bundled-resources/poe-tile-templates/base/tests/setup-dom.ts +70 -0
- package/bundled-resources/poe-tile-templates/base/tile/src/backend.ts +3 -0
- package/bundled-resources/poe-tile-templates/base/tile/styles.css +47 -0
- package/bundled-resources/poe-tile-templates/base/tsconfig.json +13 -0
- package/bundled-resources/poe-tile-templates/coverage.config.json +6 -0
- package/bundled-resources/poe-tile-templates/index.ts +27 -0
- package/bundled-resources/poe-tile-templates/package.json +31 -0
- package/bundled-resources/poe-tile-templates/phaserjs/package.partial.json +6 -0
- package/bundled-resources/poe-tile-templates/phaserjs/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/phaserjs/tile/src/entry.ts +35 -0
- package/bundled-resources/poe-tile-templates/phaserjs/ui/App.test.happydom.tsx +98 -0
- package/bundled-resources/poe-tile-templates/phaserjs/ui/App.ts +180 -0
- package/bundled-resources/poe-tile-templates/phaserjs/ui/phaser-scene.ts +174 -0
- package/bundled-resources/poe-tile-templates/phaserjs/vite.config.ts +28 -0
- package/bundled-resources/poe-tile-templates/preact/package.partial.json +9 -0
- package/bundled-resources/poe-tile-templates/preact/postcss.config.js +5 -0
- package/bundled-resources/poe-tile-templates/preact/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/preact/tile/src/entry.tsx +36 -0
- package/bundled-resources/poe-tile-templates/preact/tile/styles.css +51 -0
- package/bundled-resources/poe-tile-templates/preact/tsconfig.json +15 -0
- package/bundled-resources/poe-tile-templates/preact/ui/App.test.happydom.tsx +69 -0
- package/bundled-resources/poe-tile-templates/preact/ui/App.tsx +116 -0
- package/bundled-resources/poe-tile-templates/preact/vite.config.ts +18 -0
- package/bundled-resources/poe-tile-templates/react/package.partial.json +12 -0
- package/bundled-resources/poe-tile-templates/react/postcss.config.js +5 -0
- package/bundled-resources/poe-tile-templates/react/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/react/tile/src/entry.tsx +38 -0
- package/bundled-resources/poe-tile-templates/react/tile/styles.css +51 -0
- package/bundled-resources/poe-tile-templates/react/tsconfig.json +14 -0
- package/bundled-resources/poe-tile-templates/react/ui/App.test.happydom.tsx +71 -0
- package/bundled-resources/poe-tile-templates/react/ui/App.tsx +110 -0
- package/bundled-resources/poe-tile-templates/react/vite.config.ts +21 -0
- package/bundled-resources/poe-tile-templates/scripts/cleanup.ts +10 -0
- package/bundled-resources/poe-tile-templates/scripts/generate.ts +57 -0
- package/bundled-resources/poe-tile-templates/scripts/install-diagnostics.ts +52 -0
- package/bundled-resources/poe-tile-templates/scripts/paths.ts +7 -0
- package/bundled-resources/poe-tile-templates/scripts/sdk-dependency-key.ts +288 -0
- package/bundled-resources/poe-tile-templates/scripts/verify-all-sdks.ts +132 -0
- package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-command.ts +30 -0
- package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-tarball.ts +397 -0
- package/bundled-resources/poe-tile-templates/solidjs/_bunfig.toml +14 -0
- package/bundled-resources/poe-tile-templates/solidjs/package.partial.json +13 -0
- package/bundled-resources/poe-tile-templates/solidjs/postcss.config.js +5 -0
- package/bundled-resources/poe-tile-templates/solidjs/tests/solid-plugin.ts +49 -0
- package/bundled-resources/poe-tile-templates/solidjs/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/solidjs/tile/src/entry.tsx +36 -0
- package/bundled-resources/poe-tile-templates/solidjs/tile/styles.css +51 -0
- package/bundled-resources/poe-tile-templates/solidjs/tsconfig.json +15 -0
- package/bundled-resources/poe-tile-templates/solidjs/ui/App.test.happydom.tsx +70 -0
- package/bundled-resources/poe-tile-templates/solidjs/ui/App.tsx +129 -0
- package/bundled-resources/poe-tile-templates/solidjs/vite.config.ts +18 -0
- package/bundled-resources/poe-tile-templates/tests/check-source.test.ts +131 -0
- package/bundled-resources/poe-tile-templates/tests/dev-script.test.slow.ts +166 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/customized-manager.ts +67 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/extended-mutators.ts.txt +106 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/multiplayer-verification.test.playwright.ts.txt +103 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/replace-starter-schema.ts +67 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/phaserjs.tsx.txt +85 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/preact.tsx.txt +69 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/react.tsx.txt +73 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/seating.ts.txt +54 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/solidjs.tsx.txt +70 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/vanilla-js.tsx.txt +85 -0
- package/bundled-resources/poe-tile-templates/tests/generated-templates.test.ts +278 -0
- package/bundled-resources/poe-tile-templates/tests/happy-dom-version.test.ts +27 -0
- package/bundled-resources/poe-tile-templates/tests/install-diagnostics.test.ts +99 -0
- package/bundled-resources/poe-tile-templates/tests/native-gesture-defaults.test.ts +23 -0
- package/bundled-resources/poe-tile-templates/tests/playwright-version.test.ts +84 -0
- package/bundled-resources/poe-tile-templates/tests/render-check-scaffold.test.ts +56 -0
- package/bundled-resources/poe-tile-templates/tests/sdk-dependency-key.test.ts +129 -0
- package/bundled-resources/poe-tile-templates/tests/visual-check.test.ts +90 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/package.partial.json +3 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/tile/src/entry.ts +35 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.test.happydom.tsx +96 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.ts +113 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/vite.config.ts +17 -0
- package/cli.ts +134 -0
- package/index.ts +96 -0
- package/package.json +48 -5
- package/skills/audio-generation/.generated-by-poe-templated-docs +0 -0
- package/skills/audio-generation/SKILL.md +125 -0
- package/skills/finish-prototype/.generated-by-poe-templated-docs +0 -0
- package/skills/finish-prototype/SKILL.md +22 -0
- package/skills/help-me-build/.generated-by-poe-templated-docs +0 -0
- package/skills/help-me-build/SKILL.md +56 -0
- package/skills/image-generation/.generated-by-poe-templated-docs +0 -0
- package/skills/image-generation/SKILL.md +128 -0
- package/skills/one-shot/.generated-by-poe-templated-docs +0 -0
- package/skills/one-shot/SKILL.md +22 -0
- package/skills/platform-prototype/.generated-by-poe-templated-docs +0 -0
- package/skills/platform-prototype/SKILL.md +60 -0
- package/skills/platform-subagent/.generated-by-poe-templated-docs +0 -0
- package/skills/platform-subagent/SKILL.md +16 -0
- package/skills/poe-tiles-cli/.generated-by-poe-templated-docs +0 -0
- package/skills/poe-tiles-cli/SKILL.md +609 -0
- package/skills/poe-tiles-cli/references/device-motion.md +40 -0
- package/skills/poe-tiles-cli/references/player-updates.md +41 -0
- package/skills/prototype/.generated-by-poe-templated-docs +0 -0
- package/skills/prototype/SKILL.md +149 -0
- package/skills/publish/.generated-by-poe-templated-docs +0 -0
- package/skills/publish/SKILL.md +73 -0
- package/skills/synced-store/.generated-by-poe-templated-docs +0 -0
- package/skills/synced-store/SKILL.md +583 -0
- package/skills/synced-store/references/actions.md +85 -0
- package/skills/synced-store/references/api-patterns.md +245 -0
- package/skills/synced-store/references/architecture-scaling-and-performance.md +280 -0
- package/skills/synced-store/references/client-api-reference.md +263 -0
- package/skills/synced-store/references/data-visibility.md +95 -0
- package/skills/synced-store/references/external-stores.md +162 -0
- package/skills/synced-store/references/file-uploads.md +216 -0
- package/skills/synced-store/references/getting-user-info-of-members.md +228 -0
- package/skills/synced-store/references/limitations.md +72 -0
- package/skills/synced-store/references/live-data-limit-hook.md +131 -0
- package/skills/synced-store/references/mutator-rules.md +169 -0
- package/skills/synced-store/references/platform.md +49 -0
- package/skills/synced-store/references/schema-and-bindings.md +85 -0
- package/skills/synced-store/references/schema-libraries.md +57 -0
- package/skills/synced-store/references/schema-migrations.md +119 -0
- package/skills/synced-store/references/searchable-tables.md +27 -0
- package/skills/synced-store/references/server-forking.md +115 -0
- package/skills/synced-store/references/singleton-tables.md +61 -0
- package/skills/synced-store/references/sort-keys.md +253 -0
- package/skills/synced-store/references/ui-patterns.md +95 -0
- package/skills/tile-creator/.generated-by-poe-templated-docs +0 -0
- package/skills/tile-creator/SKILL.md +197 -0
- package/skills/tile-creator/references/assets.md +124 -0
- package/skills/tile-creator/references/backend-api.md +354 -0
- package/skills/tile-creator/references/cli-limitations.md +64 -0
- package/skills/tile-creator/references/cli.md +604 -0
- package/skills/tile-creator/references/client-api.md +2407 -0
- package/skills/tile-creator/references/composing-apps.md +166 -0
- package/skills/tile-creator/references/e2e-tests.md +55 -0
- package/skills/tile-creator/references/game-ux-best-practices.md +57 -0
- package/skills/tile-creator/references/migrating-pre-rename-tiles.md +79 -0
- package/skills/tile-creator/references/multiplayer-api-recipe.md +205 -0
- package/skills/tile-creator/references/native-results.md +100 -0
- package/skills/tile-creator/references/platform-integration.md +201 -0
- package/skills/tile-creator/references/power-report.md +199 -0
- package/skills/tile-creator/references/publish-rollout.md +166 -0
- package/skills/tile-creator/references/publishing.md +33 -0
- package/skills/tile-creator/references/push-notification-guidelines.md +58 -0
- package/skills/tile-creator/references/render-check.md +266 -0
- package/skills/tile-creator/references/running-the-client-api-on-a-server-owned-by-the-user.md +95 -0
- package/skills/tile-creator/references/safe-area-insets.md +79 -0
- package/skills/tile-creator/references/sandbox-limitations.md +32 -0
- package/skills/tile-creator/references/scaffolded-tile-folder-structure.md +48 -0
- package/skills/tile-creator/references/scaffolding-a-new-app.md +202 -0
- package/skills/tile-creator/references/simulations.md +125 -0
- package/skills/tile-creator/references/synced-store-client-reference.md +92 -0
- package/skills/tile-creator/references/troubleshooting.md +22 -0
- package/skills/tile-creator/references/turn-based-mutator.md +43 -0
- package/skills/tile-creator/references/user-erasure.md +14 -0
- package/skills/tile-creator/references/vite-plugin.md +166 -0
- package/skills/tile-creator/references/workspace-retention.md +72 -0
- package/src/admin-conversions-client.ts +28 -0
- package/src/admin-reviews-client.ts +36 -0
- package/src/api.generated.ts +1527 -0
- package/src/auth-token.ts +198 -0
- package/src/bounded-read.ts +35 -0
- package/src/bun-version.ts +33 -0
- package/src/checkout-base.ts +207 -0
- package/src/cli-bun-version.ts +16 -0
- package/src/cli-env.ts +28 -0
- package/src/cli-name.ts +23 -0
- package/src/client.ts +2474 -0
- package/src/collect-files.ts +226 -0
- package/src/commands/accounts.ts +55 -0
- package/src/commands/admin-abandon-conversion.ts +60 -0
- package/src/commands/admin-reviews.ts +66 -0
- package/src/commands/admin.ts +219 -0
- package/src/commands/auth.ts +89 -0
- package/src/commands/checkout-prototype.ts +67 -0
- package/src/commands/creator-source-capability.ts +11 -0
- package/src/commands/doctor-bun.ts +145 -0
- package/src/commands/doctor-command.ts +64 -0
- package/src/commands/doctor-package-json.ts +47 -0
- package/src/commands/doctor-sdk-pin.ts +156 -0
- package/src/commands/doctor-store-keys-lexer.ts +213 -0
- package/src/commands/doctor-store-keys-scan.ts +262 -0
- package/src/commands/doctor-store-keys.ts +196 -0
- package/src/commands/doctor.ts +371 -0
- package/src/commands/init/blank-scaffold-templates.ts +397 -0
- package/src/commands/init/index.ts +170 -0
- package/src/commands/init/internal-toolchain.ts +49 -0
- package/src/commands/init/manager-test-template.ts +107 -0
- package/src/commands/init/multiplayer-test-template.ts +217 -0
- package/src/commands/init/name-input.tsx +167 -0
- package/src/commands/init/no-store-scaffold-templates.ts +281 -0
- package/src/commands/init/no-store-scaffold.ts +134 -0
- package/src/commands/init/package-json-scripts.ts +72 -0
- package/src/commands/init/scaffold.ts +960 -0
- package/src/commands/init/sdk-tarball-url.generated.ts +4 -0
- package/src/commands/init/sdk-tarball-url.ts +31 -0
- package/src/commands/init/template-picker.tsx +147 -0
- package/src/commands/inspect-child-entry.ts +107 -0
- package/src/commands/inspect-contract.ts +87 -0
- package/src/commands/inspect-freshness.ts +217 -0
- package/src/commands/inspect-lock.ts +201 -0
- package/src/commands/inspect-options.ts +360 -0
- package/src/commands/inspect-orchestrate.ts +375 -0
- package/src/commands/inspect-process.ts +172 -0
- package/src/commands/inspect-ready.ts +65 -0
- package/src/commands/inspect-report.ts +235 -0
- package/src/commands/inspect-run-state.ts +296 -0
- package/src/commands/inspect-run.ts +157 -0
- package/src/commands/inspect-watchdog.ts +74 -0
- package/src/commands/install-joiner.ts +208 -0
- package/src/commands/login.ts +308 -0
- package/src/commands/models.ts +40 -0
- package/src/commands/parse-options.ts +36 -0
- package/src/commands/remix-package-json.ts +64 -0
- package/src/commands/remix.ts +379 -0
- package/src/commands/sdk-url.ts +141 -0
- package/src/commands/simulations.ts +133 -0
- package/src/commands/skills.ts +108 -0
- package/src/commands/store-files.ts +92 -0
- package/src/commands/stores.ts +703 -0
- package/src/commands/tiles-channel-commands.ts +115 -0
- package/src/commands/tiles-checkout.ts +351 -0
- package/src/commands/tiles-gallery-command.ts +95 -0
- package/src/commands/tiles-get-helpers.ts +27 -0
- package/src/commands/tiles-inspect.ts +276 -0
- package/src/commands/tiles-power-command.ts +308 -0
- package/src/commands/tiles-power-format.ts +396 -0
- package/src/commands/tiles-power-versions.ts +299 -0
- package/src/commands/tiles-publish-helpers.ts +145 -0
- package/src/commands/tiles-upload-command.ts +277 -0
- package/src/commands/tiles-version-commands.ts +201 -0
- package/src/commands/tiles-visibility-command.ts +103 -0
- package/src/commands/tiles.ts +257 -0
- package/src/commands/upgrade.ts +307 -0
- package/src/commit-in-progress.ts +42 -0
- package/src/creator-source-context.ts +97 -0
- package/src/creator-source-publish.ts +52 -0
- package/src/deferred-assets.ts +125 -0
- package/src/distribution.ts +28 -0
- package/src/errors.ts +61 -0
- package/src/install-command.ts +43 -0
- package/src/output.ts +62 -0
- package/src/poe-tile-config-files.ts +100 -0
- package/src/poe-tile-config-players.ts +168 -0
- package/src/poe-tile-config-remix.ts +166 -0
- package/src/poe-tile-config.ts +831 -0
- package/src/power-report-client.ts +55 -0
- package/src/prototype-startup.ts +21 -0
- package/src/publish-change-summary.ts +55 -0
- package/src/publish-overrides-validation.ts +49 -0
- package/src/publish-pack.ts +167 -0
- package/src/publish-phases.ts +57 -0
- package/src/publish-retry.ts +51 -0
- package/src/publish-tile-from-config.ts +434 -0
- package/src/recorder-stream.ts +169 -0
- package/src/remix-provenance.ts +156 -0
- package/src/resolve-client-credential.ts +71 -0
- package/src/resolve-media-uploads.ts +147 -0
- package/src/sdk-dependency.ts +54 -0
- package/src/sdk-skills.ts +85 -0
- package/src/should-skip-client-setup.ts +20 -0
- package/src/simulation-snapshot.ts +123 -0
- package/src/simulation-types.ts +74 -0
- package/src/simulations-client.ts +112 -0
- package/src/source-bundle.ts +466 -0
- package/src/staged-publish-cleanup.ts +44 -0
- package/src/staged-publish-deferred.ts +160 -0
- package/src/staged-publish.ts +401 -0
- package/src/store-file-upload.ts +268 -0
- package/src/store-request.ts +168 -0
- package/src/tar-canonical.ts +41 -0
- package/src/tar-extensions.ts +159 -0
- package/src/tar-extract.ts +193 -0
- package/src/tar-parse.ts +224 -0
- package/src/tar.ts +231 -0
- package/src/template-check-scripts.ts +18 -0
- package/src/tile-gallery-client.ts +82 -0
- package/src/types.ts +258 -0
- package/src/upload-concurrency.ts +54 -0
- package/src/whole-tile.ts +52 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,2474 @@
|
|
|
1
|
+
// owner: jyoung-q
|
|
2
|
+
/* biome-ignore-all lint/nursery/noExcessiveLinesPerFile: existing file exceeds 400 lines; add new tests or code to focused companion files instead. No new exceptions to this rule should be made. */
|
|
3
|
+
/**
|
|
4
|
+
* HTTP client for the poe-tiles REST API.
|
|
5
|
+
*
|
|
6
|
+
* Types are derived from the OpenAPI spec via codegen (see api.generated.ts).
|
|
7
|
+
* Uses cookie-based session auth: logs in once on first API call,
|
|
8
|
+
* then sends the session cookie on all subsequent requests.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { statSync } from "node:fs";
|
|
12
|
+
import { createAdminConversionsClient } from "./admin-conversions-client";
|
|
13
|
+
import { createAdminReviewsClient } from "./admin-reviews-client";
|
|
14
|
+
import { cliName } from "./cli-name.js";
|
|
15
|
+
import { createPowerReportClient } from "./power-report-client.js";
|
|
16
|
+
import { createSimulationsClient } from "./simulations-client.js";
|
|
17
|
+
import {
|
|
18
|
+
type ParsedStoreEnvelope,
|
|
19
|
+
parseStoreEnvelope,
|
|
20
|
+
sendStoreRequest,
|
|
21
|
+
serializeStoreEnvelope,
|
|
22
|
+
} from "./store-request.js";
|
|
23
|
+
import { createTileGalleryClient } from "./tile-gallery-client.js";
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
type CollectFilesOptions,
|
|
27
|
+
collectFiles,
|
|
28
|
+
} from "./collect-files.js";
|
|
29
|
+
|
|
30
|
+
import { CliError } from "./errors.js";
|
|
31
|
+
import type { TileInstancing } from "./poe-tile-config.js";
|
|
32
|
+
import type { TilePlayerCount } from "./poe-tile-config-players.js";
|
|
33
|
+
import type { PoeTileConfigRemixOf } from "./poe-tile-config-remix.js";
|
|
34
|
+
import { packPublishBundles } from "./publish-pack.js";
|
|
35
|
+
import {
|
|
36
|
+
observedSyncStep,
|
|
37
|
+
type PublishPhaseObserver,
|
|
38
|
+
} from "./publish-phases.js";
|
|
39
|
+
import type { SourceBundleVisibility } from "./source-bundle.js";
|
|
40
|
+
import { publishFormDataStaged } from "./staged-publish.js";
|
|
41
|
+
import {
|
|
42
|
+
createStoreFileUploader,
|
|
43
|
+
type StoreFileUploader,
|
|
44
|
+
} from "./store-file-upload.js";
|
|
45
|
+
import type {
|
|
46
|
+
ConnectedAccountsResponse,
|
|
47
|
+
DeleteChannelResponse,
|
|
48
|
+
LiveAutoAdvanceResponse,
|
|
49
|
+
LoginResponse,
|
|
50
|
+
LogoutResponse,
|
|
51
|
+
ModelsResponse,
|
|
52
|
+
PointsHistoryResponse,
|
|
53
|
+
PromoteLiveResponse,
|
|
54
|
+
PublishResult,
|
|
55
|
+
PublishWholeTileBundle,
|
|
56
|
+
RenameAppResponse,
|
|
57
|
+
SessionResponse,
|
|
58
|
+
SetChannelResponse,
|
|
59
|
+
SetTileVisibilityResponse,
|
|
60
|
+
SettableTileVisibility,
|
|
61
|
+
TileChannelsResponse,
|
|
62
|
+
TileGetResponse,
|
|
63
|
+
TilesListResponse,
|
|
64
|
+
TileVersionMetaResponse,
|
|
65
|
+
TileVersionsResponse,
|
|
66
|
+
UnlinkAccountResponse,
|
|
67
|
+
UsageResponse,
|
|
68
|
+
} from "./types.js";
|
|
69
|
+
|
|
70
|
+
const DEFAULT_SERVER_URL = "https://joiner.com";
|
|
71
|
+
const DEVICE_CODE_START_PATH = "/api/v1/auth/device-code/start";
|
|
72
|
+
const DEVICE_CODE_POLL_PATH = "/api/v1/auth/device-code/poll";
|
|
73
|
+
export const SYNC_LIBRARY_VERSION = 4;
|
|
74
|
+
const DEFAULT_STORE_MUTATE_TIMEOUT_MS = 15_000;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The server's `csrfCheck` middleware rejects any cookie-authenticated
|
|
78
|
+
* state-mutating request (POST/PUT/PATCH/DELETE) that omits this header.
|
|
79
|
+
* Bearer-token requests are exempt. We send it on every state-mutating
|
|
80
|
+
* call from the CLI so cookie auth doesn't 403, regardless of which
|
|
81
|
+
* routes opt into `csrfCheck` today.
|
|
82
|
+
*/
|
|
83
|
+
const CSRF_REQUESTED_WITH = "poe-tiles-cli";
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Form field name the server expects when requesting to publish as the @poe
|
|
87
|
+
* account. Kept in sync with PUBLISH_AS_POE_FIELD in @lib/tile-registry;
|
|
88
|
+
* inlined here so the CLI has no workspace deps. Drift is caught by
|
|
89
|
+
* src/workspace-sync.test.ts; tarball installability is guarded by
|
|
90
|
+
* src/packaging.test.ts.
|
|
91
|
+
*
|
|
92
|
+
* @internal Exported for drift-check tests only — not part of the public API.
|
|
93
|
+
*/
|
|
94
|
+
export const PUBLISH_AS_POE_FIELD = "publish_as_poe";
|
|
95
|
+
export const PUBLISH_AS_TILE_AUTHOR_FIELD = "publish_as_tile_author";
|
|
96
|
+
/**
|
|
97
|
+
* Form field asking the server to promote `live` to this publish in-band
|
|
98
|
+
* (`--promote`). Kept in sync with `PUBLISH_PROMOTE_FIELD` in `@lib/tile-registry`;
|
|
99
|
+
* drift caught by `src/workspace-sync.test.ts`.
|
|
100
|
+
*/
|
|
101
|
+
export const PUBLISH_PROMOTE_FIELD = "promote";
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Wire prefixes of the creator-scoped credentials the sandbox injects
|
|
105
|
+
* (`POE_TILES_PUBLISH_TOKEN`): `cst_` (creator sandbox) and `cv2_`
|
|
106
|
+
* (creator v2). These are not Poe API keys — `/auth/login` rejects them —
|
|
107
|
+
* so the client must send them directly as Bearer tokens instead of
|
|
108
|
+
* detouring through the session mint. The platform accepts them on the
|
|
109
|
+
* publish and version-management (channels/versions) endpoints, and for
|
|
110
|
+
* explicit, binding-scoped owner metadata on the detail GET routes. Metadata
|
|
111
|
+
* authorization does not turn these credentials into viewer identity.
|
|
112
|
+
* Mirrors the server's `CREATOR_SANDBOX_TOKEN_PREFIX` /
|
|
113
|
+
* `CREATOR_V2_TOKEN_PREFIX`.
|
|
114
|
+
*/
|
|
115
|
+
const CREATOR_SCOPED_TOKEN_PREFIXES = ["cst_", "cv2_"] as const;
|
|
116
|
+
|
|
117
|
+
function isCreatorScopedToken(apiKey: string): boolean {
|
|
118
|
+
return CREATOR_SCOPED_TOKEN_PREFIXES.some((prefix) =>
|
|
119
|
+
apiKey.startsWith(prefix),
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export type PublishVisibility = "public" | "unlisted" | "dev";
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A source-bundle download plus the provenance headers identifying the exact
|
|
127
|
+
* publish the bytes came from. `sourceBundleId` / `versionNumber` are `null`
|
|
128
|
+
* when the server omitted the header (no publish history, or a server older
|
|
129
|
+
* than the header) — callers must treat missing provenance as "can't record a
|
|
130
|
+
* remix attribution", never as a default.
|
|
131
|
+
*/
|
|
132
|
+
export type SourceBundleDownload = {
|
|
133
|
+
bytes: Uint8Array;
|
|
134
|
+
sourceBundleId: string | null;
|
|
135
|
+
versionNumber: number | null;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Parse the `X-Poe-Source-Version-Number` header. Anything that isn't a
|
|
140
|
+
* positive integer is treated as absent rather than coerced — a bogus version
|
|
141
|
+
* would be recorded as provenance and then rejected at publish.
|
|
142
|
+
*/
|
|
143
|
+
function parseVersionNumberHeader(raw: string | null): number | null {
|
|
144
|
+
if (raw === null || !/^\d+$/.test(raw)) return null;
|
|
145
|
+
const parsed = Number(raw);
|
|
146
|
+
return Number.isSafeInteger(parsed) && parsed >= 1 ? parsed : null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface EditSourcePublishIntent {
|
|
150
|
+
finalizeEdit: true;
|
|
151
|
+
handle?: string;
|
|
152
|
+
visibility?: PublishVisibility;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Minimal fetch signature — avoids requiring platform-specific extras like `preconnect`. */
|
|
156
|
+
type FetchLike = (
|
|
157
|
+
input: string | URL | Request,
|
|
158
|
+
init?: RequestInit,
|
|
159
|
+
) => Promise<Response>;
|
|
160
|
+
|
|
161
|
+
type WebSocketEventHandler<T> = (event: T) => void;
|
|
162
|
+
|
|
163
|
+
export interface CliWebSocket {
|
|
164
|
+
readonly readyState: number;
|
|
165
|
+
onopen: WebSocketEventHandler<unknown> | null;
|
|
166
|
+
onmessage: WebSocketEventHandler<{ data: unknown }> | null;
|
|
167
|
+
onclose: WebSocketEventHandler<{ code: number; reason?: string }> | null;
|
|
168
|
+
onerror: WebSocketEventHandler<unknown> | null;
|
|
169
|
+
send(data: string): void;
|
|
170
|
+
close(): void;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
interface WebSocketConnectOptions {
|
|
174
|
+
headers?: Record<string, string>;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export type WebSocketFactory = (
|
|
178
|
+
url: string,
|
|
179
|
+
options?: WebSocketConnectOptions,
|
|
180
|
+
) => CliWebSocket;
|
|
181
|
+
|
|
182
|
+
export type JSONValue =
|
|
183
|
+
| string
|
|
184
|
+
| number
|
|
185
|
+
| boolean
|
|
186
|
+
| null
|
|
187
|
+
| JSONValue[]
|
|
188
|
+
| { [key: string]: JSONValue };
|
|
189
|
+
|
|
190
|
+
export interface StoreMutateOptions {
|
|
191
|
+
storeTypeId: string;
|
|
192
|
+
instanceId: string;
|
|
193
|
+
mutationName: string;
|
|
194
|
+
input: JSONValue;
|
|
195
|
+
timeoutMs?: number;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export interface StoreActionOptions {
|
|
199
|
+
storeTypeId: string;
|
|
200
|
+
instanceId: string;
|
|
201
|
+
actionName: string;
|
|
202
|
+
input: JSONValue;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export interface StorePullOptions {
|
|
206
|
+
storeTypeId: string;
|
|
207
|
+
instanceId: string;
|
|
208
|
+
afterVersion?: number;
|
|
209
|
+
targetLocalBytes?: number;
|
|
210
|
+
timeoutMs?: number;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export interface StoreGetOptions {
|
|
214
|
+
storeTypeId: string;
|
|
215
|
+
instanceId: string;
|
|
216
|
+
tableName: string;
|
|
217
|
+
key: string;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export type StoreReadCursor =
|
|
221
|
+
| "$first"
|
|
222
|
+
| "$last"
|
|
223
|
+
| { sortKey?: string; itemKey: string };
|
|
224
|
+
|
|
225
|
+
export interface StoreScanOptions {
|
|
226
|
+
storeTypeId: string;
|
|
227
|
+
instanceId: string;
|
|
228
|
+
tableName: string;
|
|
229
|
+
prefix?: { sortKey?: string; itemKey?: string };
|
|
230
|
+
cursor?: StoreReadCursor;
|
|
231
|
+
limit?: number;
|
|
232
|
+
reverse?: boolean;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export interface StoreAccessOptions {
|
|
236
|
+
storeTypeId: string;
|
|
237
|
+
instanceId: string;
|
|
238
|
+
timeoutMs?: number;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export interface StoreSchemaOptions {
|
|
242
|
+
storeTypeId: string;
|
|
243
|
+
instanceId: string;
|
|
244
|
+
timeoutMs?: number;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export interface FailedMutationInfo {
|
|
248
|
+
mutation_id: number;
|
|
249
|
+
error_type: string;
|
|
250
|
+
error_message: string;
|
|
251
|
+
can_retry: boolean;
|
|
252
|
+
stack_trace?: string;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* One target store a push declared a cross-store external mutation for.
|
|
257
|
+
*
|
|
258
|
+
* Mirrors `ExternalDispatchTarget` in `@synced-store/shared`. A manifest of
|
|
259
|
+
* INTENT, not an outcome: the push response resolves at source commit, before
|
|
260
|
+
* the cross-store fan-out runs, so it can never report whether a dispatch
|
|
261
|
+
* succeeded. It previously did (`status: "committed" | "failed"` plus
|
|
262
|
+
* `targetVersion`/`targetKeys`), which is what forced every push response to
|
|
263
|
+
* wait on its whole fan-out.
|
|
264
|
+
*/
|
|
265
|
+
export interface ExternalDispatchTarget {
|
|
266
|
+
targetStoreTypeId: string;
|
|
267
|
+
targetInstanceId: string;
|
|
268
|
+
sourceKey: string;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export interface StoreMutateResult {
|
|
272
|
+
storeTypeId: string;
|
|
273
|
+
instanceId: string;
|
|
274
|
+
mutationName: string;
|
|
275
|
+
clientId: string;
|
|
276
|
+
mutationId: number;
|
|
277
|
+
requestId: string;
|
|
278
|
+
schemaVersion: number;
|
|
279
|
+
version: number;
|
|
280
|
+
failedMutations: FailedMutationInfo[];
|
|
281
|
+
/**
|
|
282
|
+
* Targets the push declared externals for. Intent, not outcome — dispatch
|
|
283
|
+
* runs after this response returns.
|
|
284
|
+
*/
|
|
285
|
+
externalDispatchTargets: ExternalDispatchTarget[];
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export interface StoreActionResult {
|
|
289
|
+
storeTypeId: string;
|
|
290
|
+
instanceId: string;
|
|
291
|
+
actionName: string;
|
|
292
|
+
result: JSONValue | null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export interface StorePullResult {
|
|
296
|
+
storeTypeId: string;
|
|
297
|
+
instanceId: string;
|
|
298
|
+
requestId: string;
|
|
299
|
+
patches: PullPatch[];
|
|
300
|
+
finalMetadata: PullFinalMetadata;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export interface StoreGetResult {
|
|
304
|
+
storeTypeId: string;
|
|
305
|
+
instanceId: string;
|
|
306
|
+
tableName: string;
|
|
307
|
+
key: string;
|
|
308
|
+
storeVersion: number;
|
|
309
|
+
found: boolean;
|
|
310
|
+
value: JSONValue | null;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export interface StoreReadItem {
|
|
314
|
+
itemKey: string;
|
|
315
|
+
sortKey: string;
|
|
316
|
+
value: JSONValue;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export interface StoreScanResult {
|
|
320
|
+
storeTypeId: string;
|
|
321
|
+
instanceId: string;
|
|
322
|
+
tableName: string;
|
|
323
|
+
storeVersion: number;
|
|
324
|
+
items: StoreReadItem[];
|
|
325
|
+
truncated: boolean;
|
|
326
|
+
nextCursor?: { sortKey?: string; itemKey: string };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export type StoreJsonSchema = {
|
|
330
|
+
[key: string]: JSONValue | undefined;
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
export type StoreTableSchemaInfo =
|
|
334
|
+
| {
|
|
335
|
+
_tag: "table";
|
|
336
|
+
valueSchema: StoreJsonSchema;
|
|
337
|
+
}
|
|
338
|
+
| {
|
|
339
|
+
_tag: "singletonTable";
|
|
340
|
+
items: Array<{ key: string; schema: StoreJsonSchema }>;
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
export interface StoreMutatorSchemaInfo {
|
|
344
|
+
name: string;
|
|
345
|
+
description?: string;
|
|
346
|
+
inputSchema: StoreJsonSchema;
|
|
347
|
+
agentTool?: { description: string };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export interface StoreActionSchemaInfo {
|
|
351
|
+
name: string;
|
|
352
|
+
description?: string;
|
|
353
|
+
inputSchema: StoreJsonSchema;
|
|
354
|
+
outputSchema: StoreJsonSchema;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export interface StoreSchemaInfo {
|
|
358
|
+
type: string;
|
|
359
|
+
schemaVersion: number;
|
|
360
|
+
tables: Record<string, StoreTableSchemaInfo>;
|
|
361
|
+
mutators: StoreMutatorSchemaInfo[];
|
|
362
|
+
actions: StoreActionSchemaInfo[];
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export interface StoreSchemaResult {
|
|
366
|
+
storeTypeId: string;
|
|
367
|
+
instanceId: string;
|
|
368
|
+
schema: StoreSchemaInfo;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export interface StoreAccessResult {
|
|
372
|
+
storeTypeId: string;
|
|
373
|
+
instanceId: string;
|
|
374
|
+
userId: string;
|
|
375
|
+
hasAccess: boolean;
|
|
376
|
+
version: number;
|
|
377
|
+
schemaVersion: number;
|
|
378
|
+
membership?: JSONValue;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export interface SlopPoeClientOptions {
|
|
382
|
+
apiKey?: string;
|
|
383
|
+
sessionToken?: string;
|
|
384
|
+
serverUrl?: string;
|
|
385
|
+
fetchFn?: FetchLike;
|
|
386
|
+
webSocketFactory?: WebSocketFactory;
|
|
387
|
+
/** The waits between publish retries; the wall clock unless a test fakes it. */
|
|
388
|
+
sleep?: ((ms: number) => Promise<void>) | undefined;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export interface DeviceCodeStartResult {
|
|
392
|
+
deviceCode: string;
|
|
393
|
+
userCode: string;
|
|
394
|
+
verificationUri: string;
|
|
395
|
+
verificationUriComplete?: string;
|
|
396
|
+
expiresIn: number;
|
|
397
|
+
interval: number;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
type DeviceCodeLoginUser = Extract<LoginResponse, { success: true }>["user"];
|
|
401
|
+
|
|
402
|
+
export type DeviceCodePollResult =
|
|
403
|
+
| { status: "pending" | "slow_down" | "expired" | "consumed" | "denied" }
|
|
404
|
+
| {
|
|
405
|
+
status: "authorized";
|
|
406
|
+
sessionToken: string;
|
|
407
|
+
user: DeviceCodeLoginUser;
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
export class SlopPoeClient {
|
|
411
|
+
private readonly apiKey: string | undefined;
|
|
412
|
+
private readonly serverUrl: string;
|
|
413
|
+
private readonly fetchFn: FetchLike;
|
|
414
|
+
private readonly sleep: ((ms: number) => Promise<void>) | undefined;
|
|
415
|
+
private readonly webSocketFactory: WebSocketFactory;
|
|
416
|
+
private sessionCookie: string | undefined;
|
|
417
|
+
private currentUserId: string | undefined;
|
|
418
|
+
readonly uploadStoreFile: StoreFileUploader;
|
|
419
|
+
readonly adminConversions: ReturnType<typeof createAdminConversionsClient>;
|
|
420
|
+
readonly simulations: ReturnType<typeof createSimulationsClient>;
|
|
421
|
+
readonly adminReviews: ReturnType<typeof createAdminReviewsClient>;
|
|
422
|
+
readonly powerReport: ReturnType<typeof createPowerReportClient>;
|
|
423
|
+
readonly tileGallery: ReturnType<typeof createTileGalleryClient>;
|
|
424
|
+
|
|
425
|
+
constructor(options: SlopPoeClientOptions) {
|
|
426
|
+
this.simulations = createSimulationsClient({
|
|
427
|
+
get: (path) => this.jsonGet(path),
|
|
428
|
+
post: (path, body) => this.jsonPost(path, body),
|
|
429
|
+
currentUserId: () => this.getCurrentUserId(),
|
|
430
|
+
openSocket: (timeoutMs) =>
|
|
431
|
+
this.openStoreSocket({
|
|
432
|
+
clientId: `poe-tiles-cli-${createRequestId()}`,
|
|
433
|
+
timeoutMs,
|
|
434
|
+
}),
|
|
435
|
+
});
|
|
436
|
+
this.adminConversions = createAdminConversionsClient({
|
|
437
|
+
get: (path) => this.jsonGet(path),
|
|
438
|
+
post: (path, body) => this.jsonPost(path, body),
|
|
439
|
+
});
|
|
440
|
+
this.adminReviews = createAdminReviewsClient({
|
|
441
|
+
get: (path) => this.jsonGet(path),
|
|
442
|
+
post: (path, body) => this.jsonPost(path, body),
|
|
443
|
+
});
|
|
444
|
+
this.powerReport = createPowerReportClient({
|
|
445
|
+
get: (path) => this.jsonGet(path),
|
|
446
|
+
sendsCreatorCredential: () => this.sendsCreatorScopedBearer(),
|
|
447
|
+
});
|
|
448
|
+
this.apiKey = options.apiKey;
|
|
449
|
+
this.serverUrl = (options.serverUrl ?? DEFAULT_SERVER_URL).replace(
|
|
450
|
+
/\/$/,
|
|
451
|
+
"",
|
|
452
|
+
);
|
|
453
|
+
this.fetchFn = options.fetchFn ?? fetch;
|
|
454
|
+
this.sleep = options.sleep;
|
|
455
|
+
this.webSocketFactory = options.webSocketFactory ?? createDefaultWebSocket;
|
|
456
|
+
this.sessionCookie = options.sessionToken?.trim() || undefined;
|
|
457
|
+
this.uploadStoreFile = createStoreFileUploader({
|
|
458
|
+
serverUrl: this.serverUrl,
|
|
459
|
+
fetchFn: this.fetchFn,
|
|
460
|
+
authenticate: async () => {
|
|
461
|
+
await this.ensureLoggedIn();
|
|
462
|
+
return this.authHeaders();
|
|
463
|
+
},
|
|
464
|
+
});
|
|
465
|
+
this.tileGallery = createTileGalleryClient({
|
|
466
|
+
serverUrl: this.serverUrl,
|
|
467
|
+
fetchFn: this.fetchFn,
|
|
468
|
+
authenticate: async () => {
|
|
469
|
+
await this.ensureLoggedIn();
|
|
470
|
+
return this.authHeaders();
|
|
471
|
+
},
|
|
472
|
+
csrfHeader: CSRF_REQUESTED_WITH,
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// ============================================
|
|
477
|
+
// Auth
|
|
478
|
+
// ============================================
|
|
479
|
+
|
|
480
|
+
async login(): Promise<LoginResponse> {
|
|
481
|
+
if (!this.apiKey) {
|
|
482
|
+
throw new CliError(
|
|
483
|
+
`No Poe API key is configured. Run \`${cliName()} login\` to create a session token.`,
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
return this.loginWithPoeApiKey(this.apiKey);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async createSessionFromPoeApiKey(apiKey: string): Promise<{
|
|
490
|
+
result: LoginResponse;
|
|
491
|
+
sessionToken: string;
|
|
492
|
+
}> {
|
|
493
|
+
const result = await this.loginWithPoeApiKey(apiKey);
|
|
494
|
+
if (!this.sessionCookie) {
|
|
495
|
+
throw new CliError("Login succeeded but no session token was returned.");
|
|
496
|
+
}
|
|
497
|
+
return { result, sessionToken: this.sessionCookie };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async startDeviceCodeLogin(
|
|
501
|
+
options: { deviceLabel?: string } = {},
|
|
502
|
+
): Promise<DeviceCodeStartResult> {
|
|
503
|
+
const res = await this.fetchFn(
|
|
504
|
+
`${this.serverUrl}${DEVICE_CODE_START_PATH}`,
|
|
505
|
+
{
|
|
506
|
+
method: "POST",
|
|
507
|
+
headers: { "Content-Type": "application/json" },
|
|
508
|
+
body: JSON.stringify({
|
|
509
|
+
...(options.deviceLabel
|
|
510
|
+
? { device_label: options.deviceLabel }
|
|
511
|
+
: undefined),
|
|
512
|
+
}),
|
|
513
|
+
},
|
|
514
|
+
);
|
|
515
|
+
if (!res.ok) {
|
|
516
|
+
throw await apiError({ op: "Device-code login", res });
|
|
517
|
+
}
|
|
518
|
+
return parseDeviceCodeStart(await res.json());
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async pollDeviceCodeLogin(options: {
|
|
522
|
+
deviceCode: string;
|
|
523
|
+
}): Promise<DeviceCodePollResult> {
|
|
524
|
+
const res = await this.fetchFn(
|
|
525
|
+
`${this.serverUrl}${DEVICE_CODE_POLL_PATH}`,
|
|
526
|
+
{
|
|
527
|
+
method: "POST",
|
|
528
|
+
headers: { "Content-Type": "application/json" },
|
|
529
|
+
body: JSON.stringify({ device_code: options.deviceCode }),
|
|
530
|
+
},
|
|
531
|
+
);
|
|
532
|
+
if (!res.ok) {
|
|
533
|
+
throw await apiError({ op: "Device-code poll", res });
|
|
534
|
+
}
|
|
535
|
+
return parseDeviceCodePoll(await res.json());
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
private async loginWithPoeApiKey(apiKey: string): Promise<LoginResponse> {
|
|
539
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/v1/auth/login`, {
|
|
540
|
+
method: "POST",
|
|
541
|
+
headers: { "Content-Type": "application/json" },
|
|
542
|
+
body: JSON.stringify({ api_key: apiKey }),
|
|
543
|
+
});
|
|
544
|
+
if (!res.ok) {
|
|
545
|
+
throw await apiError({ op: "Login", res });
|
|
546
|
+
}
|
|
547
|
+
this.extractSessionCookie(res);
|
|
548
|
+
const result = (await res.json()) as LoginResponse;
|
|
549
|
+
if (result.success) {
|
|
550
|
+
this.currentUserId = result.user.user_id;
|
|
551
|
+
}
|
|
552
|
+
return result;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
async getSession(): Promise<SessionResponse> {
|
|
556
|
+
return this.jsonGet<SessionResponse>("/api/v1/auth/session");
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
async logout(): Promise<LogoutResponse> {
|
|
560
|
+
const result = await this.jsonPost<LogoutResponse>("/api/v1/auth/logout");
|
|
561
|
+
this.sessionCookie = undefined;
|
|
562
|
+
this.currentUserId = undefined;
|
|
563
|
+
return result;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
async getUsage(): Promise<UsageResponse> {
|
|
567
|
+
return this.jsonGet<UsageResponse>("/api/v1/auth/usage");
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async getPointsHistory(): Promise<PointsHistoryResponse> {
|
|
571
|
+
return this.jsonGet<PointsHistoryResponse>("/api/v1/auth/points-history");
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// ============================================
|
|
575
|
+
// Models
|
|
576
|
+
// ============================================
|
|
577
|
+
|
|
578
|
+
async listModels(): Promise<ModelsResponse> {
|
|
579
|
+
return this.jsonGet<ModelsResponse>("/api/v1/auth/models");
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// ============================================
|
|
583
|
+
// Apps
|
|
584
|
+
// ============================================
|
|
585
|
+
|
|
586
|
+
async listTiles(): Promise<TilesListResponse> {
|
|
587
|
+
return this.jsonGet<TilesListResponse>("/api/v1/tiles");
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async getTile(
|
|
591
|
+
tileHandleOrId: string,
|
|
592
|
+
options: { includeOwnerMetadata?: boolean } = {},
|
|
593
|
+
): Promise<TileGetResponse> {
|
|
594
|
+
const query = options.includeOwnerMetadata
|
|
595
|
+
? "?includeOwnerMetadata=true"
|
|
596
|
+
: "";
|
|
597
|
+
const slashIndex = tileHandleOrId.indexOf("/");
|
|
598
|
+
if (slashIndex === -1) {
|
|
599
|
+
return this.jsonGet<TileGetResponse>(
|
|
600
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileHandleOrId)}${query}`,
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
const userHandle = tileHandleOrId.slice(0, slashIndex);
|
|
605
|
+
const appHandle = tileHandleOrId.slice(slashIndex + 1);
|
|
606
|
+
return this.jsonGet<TileGetResponse>(
|
|
607
|
+
`/api/v1/tiles/${encodeURIComponent(userHandle)}/${encodeURIComponent(appHandle)}${query}`,
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* List a tile's release channels (`live`, `staging`, and any custom ones),
|
|
613
|
+
* each with the version it points at and that version's schema version.
|
|
614
|
+
* Owner-gated — the caller must own `tileTypeId`.
|
|
615
|
+
*/
|
|
616
|
+
async getTileChannels(tileTypeId: string): Promise<TileChannelsResponse> {
|
|
617
|
+
return this.jsonGet<TileChannelsResponse>(
|
|
618
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/channels`,
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Promote (or roll back) the `live` channel of `tileTypeId` to `versionNumber`.
|
|
624
|
+
* The server refuses a rollback across a schema migration (surfaced as a
|
|
625
|
+
* `409` → `CliError`).
|
|
626
|
+
*/
|
|
627
|
+
async promoteTileLive(
|
|
628
|
+
tileTypeId: string,
|
|
629
|
+
versionNumber: number,
|
|
630
|
+
): Promise<PromoteLiveResponse> {
|
|
631
|
+
return this.jsonPost<PromoteLiveResponse>(
|
|
632
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/channels/live`,
|
|
633
|
+
{ versionNumber },
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Create or repoint a custom channel (or the reserved `staging`) of
|
|
639
|
+
* `tileTypeId` to `versionNumber`, optionally toggling `autoAdvance`. `live`
|
|
640
|
+
* is rejected by the server — move it with {@link promoteTileLive}. Owner-gated.
|
|
641
|
+
*/
|
|
642
|
+
async setTileChannel(
|
|
643
|
+
tileTypeId: string,
|
|
644
|
+
name: string,
|
|
645
|
+
versionNumber: number,
|
|
646
|
+
autoAdvance?: boolean,
|
|
647
|
+
): Promise<SetChannelResponse> {
|
|
648
|
+
const result = await this.jsonPut<SetChannelResponse>(
|
|
649
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/channels/${encodeURIComponent(name)}`,
|
|
650
|
+
autoAdvance === undefined
|
|
651
|
+
? { versionNumber }
|
|
652
|
+
: { versionNumber, autoAdvance },
|
|
653
|
+
);
|
|
654
|
+
// Absolutize here, exactly as `publishTile` does with `tileUrl`: the server
|
|
655
|
+
// returns a path, and a bare `/tile/…?channel=…` is neither clickable in a
|
|
656
|
+
// terminal nor pasteable into a browser — which is the whole point of
|
|
657
|
+
// returning it. Doing the join in the client (not each command) covers
|
|
658
|
+
// human and `--json` output from one place and keeps the two commands'
|
|
659
|
+
// output shapes consistent for scripts.
|
|
660
|
+
if (result.success) {
|
|
661
|
+
result.url = `${this.serverUrl}${result.url}`;
|
|
662
|
+
}
|
|
663
|
+
return result;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Delete a custom channel of `tileTypeId`. The reserved `live` / `staging`
|
|
668
|
+
* channels cannot be deleted (the server returns a `400`). Owner-gated.
|
|
669
|
+
*/
|
|
670
|
+
async deleteTileChannel(
|
|
671
|
+
tileTypeId: string,
|
|
672
|
+
name: string,
|
|
673
|
+
): Promise<DeleteChannelResponse> {
|
|
674
|
+
return this.jsonDelete<DeleteChannelResponse>(
|
|
675
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/channels/${encodeURIComponent(name)}`,
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* List `tileTypeId`'s published versions, newest first (one page — publish
|
|
681
|
+
* history is unbounded, but the CLI view is a recent-history glance).
|
|
682
|
+
*/
|
|
683
|
+
async listTileVersions(
|
|
684
|
+
tileTypeId: string,
|
|
685
|
+
limit = 50,
|
|
686
|
+
): Promise<TileVersionsResponse> {
|
|
687
|
+
return this.jsonGet<TileVersionsResponse>(
|
|
688
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/versions?limit=${limit}`,
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* Patch one published version's creator-supplied metadata. Tri-state per
|
|
694
|
+
* field: present → set (`null` clears back to the default), absent →
|
|
695
|
+
* unchanged — so a name edit never clobbers the notes. Owner-gated.
|
|
696
|
+
*/
|
|
697
|
+
async updateTileVersionMeta(
|
|
698
|
+
tileTypeId: string,
|
|
699
|
+
versionNumber: number,
|
|
700
|
+
patch: { displayName?: string | null; notes?: string | null },
|
|
701
|
+
): Promise<TileVersionMetaResponse> {
|
|
702
|
+
return this.jsonPatch<TileVersionMetaResponse>(
|
|
703
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/versions/${versionNumber}`,
|
|
704
|
+
patch,
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Store `tileTypeId`'s "Auto-Advance Live" preference: whether a publish
|
|
710
|
+
* promotes `live` to the new version immediately (default ON), or leaves it
|
|
711
|
+
* for an explicit `tiles promote`. Owner-gated; 404 for a never-published
|
|
712
|
+
* tile (no live channel row exists to hold the preference).
|
|
713
|
+
*/
|
|
714
|
+
async setLiveAutoAdvance(
|
|
715
|
+
tileTypeId: string,
|
|
716
|
+
autoAdvance: boolean,
|
|
717
|
+
): Promise<LiveAutoAdvanceResponse> {
|
|
718
|
+
return this.jsonPut<LiveAutoAdvanceResponse>(
|
|
719
|
+
`/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/channels/live/auto-advance`,
|
|
720
|
+
{ autoAdvance },
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Download a published app's source tarball together with the provenance
|
|
726
|
+
* headers describing the branch point: the content-addressed
|
|
727
|
+
* `X-Poe-Source-Bundle-Id` and the publish `X-Poe-Source-Version-Number`.
|
|
728
|
+
*
|
|
729
|
+
* They ride the SAME response as the bytes on purpose — fetching the
|
|
730
|
+
* version separately could straddle a republish and record a pair that
|
|
731
|
+
* never existed, which the publish trust boundary would then reject.
|
|
732
|
+
* `versionNumber` is `null` when the app has no publish history or the
|
|
733
|
+
* server predates the header.
|
|
734
|
+
*/
|
|
735
|
+
async downloadSourceBundle(
|
|
736
|
+
tileTypeId: string,
|
|
737
|
+
): Promise<SourceBundleDownload> {
|
|
738
|
+
await this.ensureLoggedIn();
|
|
739
|
+
const res = await this.fetchFn(
|
|
740
|
+
`${this.serverUrl}/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/source-bundle`,
|
|
741
|
+
{
|
|
742
|
+
headers: this.authHeaders(),
|
|
743
|
+
},
|
|
744
|
+
);
|
|
745
|
+
if (!res.ok) {
|
|
746
|
+
throw await apiError({ op: "Request", res });
|
|
747
|
+
}
|
|
748
|
+
const contentLength = res.headers.get("Content-Length");
|
|
749
|
+
const expectedBytes =
|
|
750
|
+
contentLength === null ? Number.NaN : Number(contentLength);
|
|
751
|
+
if (
|
|
752
|
+
contentLength === null ||
|
|
753
|
+
!/^\d+$/.test(contentLength) ||
|
|
754
|
+
!Number.isSafeInteger(expectedBytes)
|
|
755
|
+
) {
|
|
756
|
+
throw new CliError(
|
|
757
|
+
"Source bundle response is missing a valid Content-Length header",
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
761
|
+
if (bytes.byteLength !== expectedBytes) {
|
|
762
|
+
const mismatch =
|
|
763
|
+
bytes.byteLength < expectedBytes ? "was truncated" : "exceeded its";
|
|
764
|
+
throw new CliError(
|
|
765
|
+
`Source bundle download ${mismatch} declared Content-Length (expected ${expectedBytes} bytes, received ${bytes.byteLength})`,
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
return {
|
|
769
|
+
bytes,
|
|
770
|
+
sourceBundleId: res.headers.get("X-Poe-Source-Bundle-Id"),
|
|
771
|
+
versionNumber: parseVersionNumberHeader(
|
|
772
|
+
res.headers.get("X-Poe-Source-Version-Number"),
|
|
773
|
+
),
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Rewrite the handle of an app owned by the caller. `tileTypeId` must be the
|
|
779
|
+
* canonical app ID (UUID-shaped or first-party numeric), NOT the
|
|
780
|
+
* `userHandle/appHandle` form: the server route is keyed on the
|
|
781
|
+
* canonical id (`PUT /tiles/by-id/{tileTypeId}/handle`). The CLI command
|
|
782
|
+
* resolves a slash-form argument via `getTile` first.
|
|
783
|
+
*
|
|
784
|
+
* When `useAsPoeAccount` is true, the request is sent with Bearer auth
|
|
785
|
+
* (skipping the session-cookie login) and `publish_as_poe: true` in the
|
|
786
|
+
* body. The server requires the resolved API-key user to be in its
|
|
787
|
+
* `POE_PUBLISH_ACCOUNTS` allowlist; non-allowlisted callers receive 403.
|
|
788
|
+
* The same affordance backs staged publish commits with `publishAsPoe`; the
|
|
789
|
+
* rename mirror lets first-party Tile handles be rotated without a
|
|
790
|
+
* republish.
|
|
791
|
+
*
|
|
792
|
+
* Server-side error mapping: 400 invalid handle, 403 caller not
|
|
793
|
+
* allowlisted (publish-as-poe only) or missing X-Requested-With (cookie
|
|
794
|
+
* path), 404 not found / not yours (uniform), 409 target handle already
|
|
795
|
+
* taken by the same creator.
|
|
796
|
+
*/
|
|
797
|
+
async renameTile(
|
|
798
|
+
tileTypeId: string,
|
|
799
|
+
handle: string,
|
|
800
|
+
opts?: { useAsPoeAccount?: boolean },
|
|
801
|
+
): Promise<RenameAppResponse> {
|
|
802
|
+
const path = `/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/handle`;
|
|
803
|
+
if (opts?.useAsPoeAccount) {
|
|
804
|
+
// Bearer-direct: same wire shape as `publishTile --publish-as-poe`
|
|
805
|
+
// (Authorization: Bearer + opaque body field). Skips ensureLoggedIn
|
|
806
|
+
// so we don't burn a roundtrip on the cookie dance — the server
|
|
807
|
+
// only needs the Bearer to resolve the caller before checking the
|
|
808
|
+
// poe-publish allowlist.
|
|
809
|
+
if (!this.apiKey) {
|
|
810
|
+
throw new Error(
|
|
811
|
+
"renameTile with useAsPoeAccount requires an API key — set POE_API_KEY or pass `apiKey` to the client.",
|
|
812
|
+
);
|
|
813
|
+
}
|
|
814
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
815
|
+
method: "PUT",
|
|
816
|
+
headers: {
|
|
817
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
818
|
+
"Content-Type": "application/json",
|
|
819
|
+
},
|
|
820
|
+
body: JSON.stringify({ handle, publish_as_poe: true }),
|
|
821
|
+
});
|
|
822
|
+
if (!res.ok) {
|
|
823
|
+
throw await apiError({ op: "Request", res });
|
|
824
|
+
}
|
|
825
|
+
return res.json() as Promise<RenameAppResponse>;
|
|
826
|
+
}
|
|
827
|
+
return this.jsonPut<RenameAppResponse>(path, { handle });
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Move a tile in or out of public discovery.
|
|
832
|
+
*
|
|
833
|
+
* The only way to change visibility. Publishing deliberately cannot: a
|
|
834
|
+
* publish uploads a bundle, and a tile's discoverability is a separate
|
|
835
|
+
* decision that outlives any one of them. A new tile is unlisted, and this
|
|
836
|
+
* is what lists it.
|
|
837
|
+
*
|
|
838
|
+
* `dev` is not offered here, matching the route: it gates synthetic test
|
|
839
|
+
* users rather than discovery, and no creator-facing surface explains it.
|
|
840
|
+
*/
|
|
841
|
+
async setTileVisibility(
|
|
842
|
+
tileTypeId: string,
|
|
843
|
+
visibility: SettableTileVisibility,
|
|
844
|
+
opts?: { useAsPoeAccount?: boolean },
|
|
845
|
+
): Promise<SetTileVisibilityResponse> {
|
|
846
|
+
const path = `/api/v1/tiles/by-id/${encodeURIComponent(tileTypeId)}/visibility`;
|
|
847
|
+
return this.jsonPut<SetTileVisibilityResponse>(path, {
|
|
848
|
+
visibility,
|
|
849
|
+
...(opts?.useAsPoeAccount ? { publish_as_poe: true } : {}),
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
private async ensureTileAuthorPublishSupported(
|
|
854
|
+
handle: string,
|
|
855
|
+
): Promise<void> {
|
|
856
|
+
if (!this.apiKey) {
|
|
857
|
+
throw new Error(
|
|
858
|
+
"Publishing as a configured Tile author requires an API key.",
|
|
859
|
+
);
|
|
860
|
+
}
|
|
861
|
+
// This separate route is a rollout gate: an older server returns 404,
|
|
862
|
+
// so release automation fails before it can publish under the caller or
|
|
863
|
+
// unlist the legacy @poe row with the new form field ignored.
|
|
864
|
+
const response = await this.fetchFn(
|
|
865
|
+
`${this.serverUrl}/api/v1/publish-author-config/${encodeURIComponent(handle)}`,
|
|
866
|
+
{ headers: { Authorization: `Bearer ${this.apiKey}` } },
|
|
867
|
+
);
|
|
868
|
+
if (!response.ok) {
|
|
869
|
+
throw await apiError({ op: "Publish", res: response });
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Ask the server which account release automation should publish this
|
|
875
|
+
* handle as. The server decides from live registry state (who owns the
|
|
876
|
+
* canonical row right now), which is what lets a post-merge publish and
|
|
877
|
+
* the deploy-time ownership migration race in either order and still
|
|
878
|
+
* converge — the script cannot know the answer on its own.
|
|
879
|
+
*
|
|
880
|
+
* **Fails closed.** A server too old to report `publishIdentity` fails this
|
|
881
|
+
* tile's publish rather than defaulting. Defaulting to `"poe"` would be
|
|
882
|
+
* wrong in the one genuinely dangerous skew — a worker rolled back across
|
|
883
|
+
* the migration boundary — where a `"poe"` publish against already-migrated
|
|
884
|
+
* data would mint a fresh @poe row on a server that lacks the no-create
|
|
885
|
+
* backstop. A failed publish self-heals on the next merge; a duplicated
|
|
886
|
+
* tile does not.
|
|
887
|
+
*/
|
|
888
|
+
private async resolveReleasePublishIdentity(
|
|
889
|
+
handle: string,
|
|
890
|
+
): Promise<"poe" | "tile-author"> {
|
|
891
|
+
if (!this.apiKey) {
|
|
892
|
+
throw new Error(
|
|
893
|
+
"Publishing with the configured release identity requires an API key.",
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
const response = await this.fetchFn(
|
|
897
|
+
`${this.serverUrl}/api/v1/publish-author-config/${encodeURIComponent(handle)}`,
|
|
898
|
+
{ headers: { Authorization: `Bearer ${this.apiKey}` } },
|
|
899
|
+
);
|
|
900
|
+
if (!response.ok) {
|
|
901
|
+
throw await apiError({ op: "Publish", res: response });
|
|
902
|
+
}
|
|
903
|
+
const body = (await response.json()) as { publishIdentity?: unknown };
|
|
904
|
+
if (
|
|
905
|
+
body.publishIdentity !== "poe" &&
|
|
906
|
+
body.publishIdentity !== "tile-author"
|
|
907
|
+
) {
|
|
908
|
+
throw new Error(
|
|
909
|
+
`Server did not report a publish identity for "${handle}". It is older than the Tile ownership migration; re-run this publish after the worker deploy completes.`,
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
return body.publishIdentity;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Which account this publish lands under. Either the caller stated it
|
|
917
|
+
* outright, or (release automation) the server is asked — see
|
|
918
|
+
* {@link resolveReleasePublishIdentity}.
|
|
919
|
+
*/
|
|
920
|
+
private async resolvePublishAccount(
|
|
921
|
+
handle: string,
|
|
922
|
+
options: {
|
|
923
|
+
publishAsPoe?: boolean;
|
|
924
|
+
publishAsTileAuthor?: boolean;
|
|
925
|
+
publishAsReleaseIdentity?: boolean;
|
|
926
|
+
},
|
|
927
|
+
): Promise<{ asPoe: boolean; asTileAuthor: boolean }> {
|
|
928
|
+
if (options.publishAsReleaseIdentity) {
|
|
929
|
+
const identity = await this.resolveReleasePublishIdentity(handle);
|
|
930
|
+
return {
|
|
931
|
+
asPoe: identity === "poe",
|
|
932
|
+
asTileAuthor: identity === "tile-author",
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
return {
|
|
936
|
+
asPoe: options.publishAsPoe === true,
|
|
937
|
+
asTileAuthor: options.publishAsTileAuthor === true,
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
async publishTile(options: {
|
|
942
|
+
handle: string;
|
|
943
|
+
dir: string;
|
|
944
|
+
/** Creator’s explicit SDK-free prototype phase, independent of backend presence. */
|
|
945
|
+
prototype?: boolean;
|
|
946
|
+
/** `dir` is the tile root; see `TILE_ROOT_RUNTIME_IGNORES`. */
|
|
947
|
+
runtimeBundleAtTileRoot?: boolean;
|
|
948
|
+
editSourcePublishIntent?: EditSourcePublishIntent;
|
|
949
|
+
/** When true, publish under the @poe system account. Requires allowlisted API key. */
|
|
950
|
+
publishAsPoe?: boolean;
|
|
951
|
+
/** When true, publish under this handle's checked-in first-party author. */
|
|
952
|
+
publishAsTileAuthor?: boolean;
|
|
953
|
+
/**
|
|
954
|
+
* Release automation only. Asks the server which identity to publish
|
|
955
|
+
* this handle as (`@poe` while it still owns the canonical row, the
|
|
956
|
+
* configured author once ownership has migrated) and publishes as that.
|
|
957
|
+
* Mutually exclusive with the two flags above.
|
|
958
|
+
*/
|
|
959
|
+
publishAsReleaseIdentity?: boolean;
|
|
960
|
+
/**
|
|
961
|
+
* When true, promote `live` to this publish in-band (`--promote`). Without
|
|
962
|
+
* it a publish only advances `staging`. The server promotes under the same
|
|
963
|
+
* request identity that published, so it composes with the `publishAs*`
|
|
964
|
+
* flags; the promoted version rides back on the response as
|
|
965
|
+
* `promotedToLiveVersion`.
|
|
966
|
+
*/
|
|
967
|
+
promote?: boolean;
|
|
968
|
+
/**
|
|
969
|
+
* Visibility for this publish. Omit to let first publish default to
|
|
970
|
+
* public and to preserve the current visibility on re-publish.
|
|
971
|
+
*/
|
|
972
|
+
visibility?: PublishVisibility;
|
|
973
|
+
/**
|
|
974
|
+
* When true, flag this app as a development/preview app in the
|
|
975
|
+
* registry. Currently this gates whether the synced-store backend
|
|
976
|
+
* accepts synthetic test-user origins on connections to this app.
|
|
977
|
+
*/
|
|
978
|
+
tileAllowsTestUsers?: boolean;
|
|
979
|
+
/**
|
|
980
|
+
* Optional source-code bundle. When set, the CLI walks `sourceBundle.dir`,
|
|
981
|
+
* builds a gzipped tar (applying the built-in defaults + `.gitignore`
|
|
982
|
+
* + `sourceBundle.ignoreFile`), and attaches it as `source_bundle` on
|
|
983
|
+
* the publish form. `sourceBundle.visibility` is forwarded as
|
|
984
|
+
* `source_bundle_visibility`. See `src/source-bundle.ts`.
|
|
985
|
+
*/
|
|
986
|
+
sourceBundle?: {
|
|
987
|
+
dir: string;
|
|
988
|
+
visibility: SourceBundleVisibility;
|
|
989
|
+
ignoreFile?: string;
|
|
990
|
+
};
|
|
991
|
+
/**
|
|
992
|
+
* Optional app icon. `{ bytes, mimeType }` uploads a local image,
|
|
993
|
+
* `{ url }` stores an `https://` URL as-is, and `{ clear: true }`
|
|
994
|
+
* tells the server to drop any existing picture. Undefined leaves
|
|
995
|
+
* the existing value alone (preserve-on-omit).
|
|
996
|
+
*/
|
|
997
|
+
profilePicture?:
|
|
998
|
+
| { bytes: Uint8Array; mimeType: string }
|
|
999
|
+
| { url: string }
|
|
1000
|
+
| { clear: true };
|
|
1001
|
+
/** Optional ≤140-char tagline. `{ value: "" }` is sent as the
|
|
1002
|
+
* explicit empty string; the server treats that as "clear this
|
|
1003
|
+
* column." Pass `undefined` (or omit) to leave the existing
|
|
1004
|
+
* value alone. */
|
|
1005
|
+
shortDescription?: { value: string };
|
|
1006
|
+
/** Optional markdown body (UTF-8 bytes ≤16 KB). `{ clear: true }`
|
|
1007
|
+
* drops the existing column on the server; otherwise the
|
|
1008
|
+
* contents replace it. */
|
|
1009
|
+
longDescription?: { value: string } | { clear: true };
|
|
1010
|
+
/** Optional human-friendly display name (≤80 chars). Overrides the
|
|
1011
|
+
* kebab-case handle on all user-facing surfaces. */
|
|
1012
|
+
displayName?: { value: string };
|
|
1013
|
+
/** Optional concise user-facing summary of this specific publish.
|
|
1014
|
+
* Used by Creator's chat receipt; omitted for other publish flows. */
|
|
1015
|
+
changeSummary?: string;
|
|
1016
|
+
/** Optional publish-time version label (≤60 chars) shown in the
|
|
1017
|
+
* version-history UI instead of the default "Version N". */
|
|
1018
|
+
versionName?: string;
|
|
1019
|
+
/** Optional free-form what-changed notes (≤2000 chars) stored on the
|
|
1020
|
+
* new version row. Defaults server-side to changeSummary when omitted. */
|
|
1021
|
+
versionNotes?: string;
|
|
1022
|
+
/**
|
|
1023
|
+
* Optional ordered detail-card screenshots. Each entry is a local
|
|
1024
|
+
* image (`{ bytes, mimeType }`, uploaded) or an `https://` URL
|
|
1025
|
+
* (`{ url }`, stored as-is). An empty array clears existing
|
|
1026
|
+
* screenshots; omitting the field preserves them.
|
|
1027
|
+
*/
|
|
1028
|
+
screenshots?: Array<
|
|
1029
|
+
{ bytes: Uint8Array; mimeType: string } | { url: string }
|
|
1030
|
+
>;
|
|
1031
|
+
/**
|
|
1032
|
+
* Optional player-count facet. `{ value }` sets it; `{ clear: true }`
|
|
1033
|
+
* sends the clear sentinel (the server drops the existing value);
|
|
1034
|
+
* omitting the field preserves it (preserve-on-republish).
|
|
1035
|
+
*/
|
|
1036
|
+
players?: { value: TilePlayerCount } | { clear: true };
|
|
1037
|
+
/**
|
|
1038
|
+
* Optional remix provenance. `{ value }` claims that this app was remixed
|
|
1039
|
+
* from that app/publish; `{ clear: true }` sends the clear sentinel (the
|
|
1040
|
+
* server drops the existing attribution); omitting preserves it.
|
|
1041
|
+
*
|
|
1042
|
+
* The claim is NOT verified server-side: publish checks its shape and
|
|
1043
|
+
* never looks up the named app. A malformed value is a 400; an
|
|
1044
|
+
* unresolvable one is stored and simply renders nothing.
|
|
1045
|
+
*/
|
|
1046
|
+
remixOf?: { value: PoeTileConfigRemixOf } | { clear: true };
|
|
1047
|
+
/**
|
|
1048
|
+
* Optional instancing mode. A mode literal sets it (`per-launch` IS the
|
|
1049
|
+
* default state — no clear sentinel); omitting the field preserves it
|
|
1050
|
+
* (preserve-on-republish).
|
|
1051
|
+
*/
|
|
1052
|
+
instancing?: TileInstancing;
|
|
1053
|
+
/** Which bundle holds the whole tile; in-process callers only. */
|
|
1054
|
+
wholeTileBundle?: PublishWholeTileBundle;
|
|
1055
|
+
/**
|
|
1056
|
+
* Optional gameplay preview video. `{ value: { src, poster } }` uploads
|
|
1057
|
+
* the mp4 + poster (both local bytes — no URL pass-through); `{ clear:
|
|
1058
|
+
* true }` sends the clear sentinel; omitting preserves it. Independent of
|
|
1059
|
+
* `screenshots`.
|
|
1060
|
+
*/
|
|
1061
|
+
video?:
|
|
1062
|
+
| {
|
|
1063
|
+
value: {
|
|
1064
|
+
src: { bytes: Uint8Array; mimeType: string };
|
|
1065
|
+
poster: { bytes: Uint8Array; mimeType: string };
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
| { clear: true };
|
|
1069
|
+
/** Client-side phase timings, for a caller that measures. See `publish-phases.ts`. */
|
|
1070
|
+
observe?: PublishPhaseObserver;
|
|
1071
|
+
}): Promise<PublishResult> {
|
|
1072
|
+
const { handle, dir } = options;
|
|
1073
|
+
|
|
1074
|
+
const stat = statSync(dir, { throwIfNoEntry: false });
|
|
1075
|
+
if (!stat?.isDirectory()) {
|
|
1076
|
+
throw new Error(`Directory not found: ${dir}`);
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
// Timed as one phase, recorded whether it returns or throws.
|
|
1080
|
+
const { runtime, sourceTarGz } = observedSyncStep(
|
|
1081
|
+
options.observe,
|
|
1082
|
+
"pack",
|
|
1083
|
+
() => packPublishBundles(dir, options),
|
|
1084
|
+
);
|
|
1085
|
+
|
|
1086
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Existing function exceeds the cognitive-complexity limit; keep the rule enabled for new code.
|
|
1087
|
+
const buildFormData = (): FormData => {
|
|
1088
|
+
const formData = new FormData();
|
|
1089
|
+
formData.append("handle", handle);
|
|
1090
|
+
formData.append(
|
|
1091
|
+
"bundle",
|
|
1092
|
+
new Blob([new Uint8Array(runtime.client)], {
|
|
1093
|
+
type: "application/gzip",
|
|
1094
|
+
}),
|
|
1095
|
+
"bundle.tar.gz",
|
|
1096
|
+
);
|
|
1097
|
+
if (runtime.backend) {
|
|
1098
|
+
formData.append(
|
|
1099
|
+
"backend_bundle",
|
|
1100
|
+
new Blob([new Uint8Array(runtime.backend)], {
|
|
1101
|
+
type: "application/gzip",
|
|
1102
|
+
}),
|
|
1103
|
+
"backend-bundle.tar.gz",
|
|
1104
|
+
);
|
|
1105
|
+
}
|
|
1106
|
+
if (asPoe) {
|
|
1107
|
+
formData.append(PUBLISH_AS_POE_FIELD, "true");
|
|
1108
|
+
}
|
|
1109
|
+
if (asTileAuthor) {
|
|
1110
|
+
formData.append(PUBLISH_AS_TILE_AUTHOR_FIELD, "true");
|
|
1111
|
+
}
|
|
1112
|
+
if (options.promote) {
|
|
1113
|
+
formData.append(PUBLISH_PROMOTE_FIELD, "true");
|
|
1114
|
+
}
|
|
1115
|
+
if (options.visibility !== undefined) {
|
|
1116
|
+
formData.append("visibility", options.visibility);
|
|
1117
|
+
}
|
|
1118
|
+
if (options.editSourcePublishIntent !== undefined) {
|
|
1119
|
+
formData.append("finalize_edit", "true");
|
|
1120
|
+
if (options.editSourcePublishIntent.handle !== undefined) {
|
|
1121
|
+
formData.append(
|
|
1122
|
+
"edit_handle",
|
|
1123
|
+
options.editSourcePublishIntent.handle,
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
if (options.editSourcePublishIntent.visibility !== undefined) {
|
|
1127
|
+
formData.append(
|
|
1128
|
+
"edit_visibility",
|
|
1129
|
+
options.editSourcePublishIntent.visibility,
|
|
1130
|
+
);
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
if (options.tileAllowsTestUsers) {
|
|
1134
|
+
formData.append("is_dev_tile", "true");
|
|
1135
|
+
}
|
|
1136
|
+
if (sourceTarGz && options.sourceBundle) {
|
|
1137
|
+
formData.append(
|
|
1138
|
+
"source_bundle",
|
|
1139
|
+
new Blob([new Uint8Array(sourceTarGz)], {
|
|
1140
|
+
type: "application/gzip",
|
|
1141
|
+
}),
|
|
1142
|
+
"source-bundle.tar.gz",
|
|
1143
|
+
);
|
|
1144
|
+
formData.append(
|
|
1145
|
+
"source_bundle_visibility",
|
|
1146
|
+
options.sourceBundle.visibility,
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
if (options.profilePicture) {
|
|
1150
|
+
if ("clear" in options.profilePicture) {
|
|
1151
|
+
// Empty File marks the column for server-side clear.
|
|
1152
|
+
formData.append(
|
|
1153
|
+
"profile_picture",
|
|
1154
|
+
new Blob([], { type: "application/octet-stream" }),
|
|
1155
|
+
"empty",
|
|
1156
|
+
);
|
|
1157
|
+
} else if ("bytes" in options.profilePicture) {
|
|
1158
|
+
formData.append(
|
|
1159
|
+
"profile_picture",
|
|
1160
|
+
new Blob([new Uint8Array(options.profilePicture.bytes)], {
|
|
1161
|
+
type: options.profilePicture.mimeType,
|
|
1162
|
+
}),
|
|
1163
|
+
"profile-picture",
|
|
1164
|
+
);
|
|
1165
|
+
} else {
|
|
1166
|
+
formData.append("profile_picture_url", options.profilePicture.url);
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
if (options.shortDescription) {
|
|
1170
|
+
formData.append("short_description", options.shortDescription.value);
|
|
1171
|
+
}
|
|
1172
|
+
if (options.longDescription) {
|
|
1173
|
+
if ("clear" in options.longDescription) {
|
|
1174
|
+
formData.append("long_description", "");
|
|
1175
|
+
} else {
|
|
1176
|
+
formData.append("long_description", options.longDescription.value);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
if (options.displayName) {
|
|
1180
|
+
formData.append("display_name", options.displayName.value);
|
|
1181
|
+
}
|
|
1182
|
+
if (options.changeSummary) {
|
|
1183
|
+
formData.append("change_summary", options.changeSummary);
|
|
1184
|
+
}
|
|
1185
|
+
if (options.versionName) {
|
|
1186
|
+
formData.append("version_name", options.versionName);
|
|
1187
|
+
}
|
|
1188
|
+
if (options.versionNotes) {
|
|
1189
|
+
formData.append("version_notes", options.versionNotes);
|
|
1190
|
+
}
|
|
1191
|
+
if (options.screenshots) {
|
|
1192
|
+
// Ordered manifest + one File part per uploaded item, matching the
|
|
1193
|
+
// server's wire format in `tile-publish-screenshots.ts`. An empty
|
|
1194
|
+
// array serializes to `[]`, which the server reads as "clear".
|
|
1195
|
+
const manifest = options.screenshots.map((shot, i) => {
|
|
1196
|
+
if ("url" in shot) return { kind: "url", url: shot.url };
|
|
1197
|
+
const field = `screenshot_file_${i}`;
|
|
1198
|
+
formData.append(
|
|
1199
|
+
field,
|
|
1200
|
+
new Blob([new Uint8Array(shot.bytes)], { type: shot.mimeType }),
|
|
1201
|
+
field,
|
|
1202
|
+
);
|
|
1203
|
+
return { kind: "file", field };
|
|
1204
|
+
});
|
|
1205
|
+
formData.append("screenshots", JSON.stringify(manifest));
|
|
1206
|
+
}
|
|
1207
|
+
if (options.players) {
|
|
1208
|
+
// The field always holds JSON: an object sets the value, and the
|
|
1209
|
+
// JSON literal `null` is the clear sentinel. Absent → preserve.
|
|
1210
|
+
// Mirrors the server's wire format in `tile-publish-players.ts`.
|
|
1211
|
+
formData.append(
|
|
1212
|
+
"players",
|
|
1213
|
+
JSON.stringify(
|
|
1214
|
+
"clear" in options.players ? null : options.players.value,
|
|
1215
|
+
),
|
|
1216
|
+
);
|
|
1217
|
+
}
|
|
1218
|
+
if (options.remixOf) {
|
|
1219
|
+
// The field always holds JSON: an object sets the claim, and the
|
|
1220
|
+
// JSON literal `null` is the clear sentinel. Absent → preserve.
|
|
1221
|
+
// Mirrors the server's wire format in `tile-publish-remix.ts`.
|
|
1222
|
+
formData.append(
|
|
1223
|
+
"remix_of",
|
|
1224
|
+
JSON.stringify(
|
|
1225
|
+
"clear" in options.remixOf ? null : options.remixOf.value,
|
|
1226
|
+
),
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
if (options.instancing !== undefined) {
|
|
1230
|
+
// Exact "per-launch"/"per-context" literals, matching the server's
|
|
1231
|
+
// wire format in `tile-publish-instancing.ts`. Absent → preserve.
|
|
1232
|
+
formData.append("instancing", options.instancing);
|
|
1233
|
+
}
|
|
1234
|
+
if (options.wholeTileBundle !== undefined) {
|
|
1235
|
+
formData.append("whole_tile_bundle", options.wholeTileBundle);
|
|
1236
|
+
}
|
|
1237
|
+
if (options.video) {
|
|
1238
|
+
// The `video` field holds JSON: a `{ src, poster }` manifest naming
|
|
1239
|
+
// the two File parts sets the video; the JSON literal `null` is the
|
|
1240
|
+
// clear sentinel. Absent → preserve. Mirrors the server's wire
|
|
1241
|
+
// format in `tile-publish-videos.ts`.
|
|
1242
|
+
if ("clear" in options.video) {
|
|
1243
|
+
formData.append("video", JSON.stringify(null));
|
|
1244
|
+
} else {
|
|
1245
|
+
const { src, poster } = options.video.value;
|
|
1246
|
+
formData.append(
|
|
1247
|
+
"video_file",
|
|
1248
|
+
new Blob([new Uint8Array(src.bytes)], { type: src.mimeType }),
|
|
1249
|
+
"video_file",
|
|
1250
|
+
);
|
|
1251
|
+
formData.append(
|
|
1252
|
+
"video_poster_file",
|
|
1253
|
+
new Blob([new Uint8Array(poster.bytes)], { type: poster.mimeType }),
|
|
1254
|
+
"video_poster_file",
|
|
1255
|
+
);
|
|
1256
|
+
formData.append(
|
|
1257
|
+
"video",
|
|
1258
|
+
JSON.stringify({ src: "video_file", poster: "video_poster_file" }),
|
|
1259
|
+
);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
return formData;
|
|
1263
|
+
};
|
|
1264
|
+
|
|
1265
|
+
// Resolved before any form data is built: with
|
|
1266
|
+
// `--publish-as-release-identity` the server, not the caller, decides
|
|
1267
|
+
// which account this publish lands under.
|
|
1268
|
+
const { asPoe, asTileAuthor } = await this.resolvePublishAccount(
|
|
1269
|
+
handle,
|
|
1270
|
+
options,
|
|
1271
|
+
);
|
|
1272
|
+
|
|
1273
|
+
const publishTo = async (): Promise<Response> => {
|
|
1274
|
+
const useBearerAuth = asPoe || asTileAuthor || !this.sessionCookie;
|
|
1275
|
+
if (useBearerAuth && !this.apiKey) {
|
|
1276
|
+
throw new Error(
|
|
1277
|
+
`Publishing with Bearer auth requires an API key. Run \`${cliName()} login\` to create a session token or set POE_API_KEY.`,
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
if (!useBearerAuth) {
|
|
1281
|
+
await this.ensureLoggedIn();
|
|
1282
|
+
}
|
|
1283
|
+
return publishFormDataStaged({
|
|
1284
|
+
serverUrl: this.serverUrl,
|
|
1285
|
+
fetchFn: this.fetchFn,
|
|
1286
|
+
headers: useBearerAuth
|
|
1287
|
+
? { Authorization: `Bearer ${this.apiKey}` }
|
|
1288
|
+
: {
|
|
1289
|
+
...this.authHeaders(),
|
|
1290
|
+
"X-Requested-With": CSRF_REQUESTED_WITH,
|
|
1291
|
+
},
|
|
1292
|
+
formData: buildFormData(),
|
|
1293
|
+
observe: options.observe,
|
|
1294
|
+
sleep: this.sleep,
|
|
1295
|
+
deferredFiles: runtime.deferred,
|
|
1296
|
+
});
|
|
1297
|
+
};
|
|
1298
|
+
|
|
1299
|
+
if (asTileAuthor && !options.publishAsReleaseIdentity) {
|
|
1300
|
+
await this.ensureTileAuthorPublishSupported(handle);
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const res = await publishTo();
|
|
1304
|
+
|
|
1305
|
+
if (!res.ok) {
|
|
1306
|
+
throw await apiError({ op: "Publish", res });
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
const result = (await res.json()) as PublishResult;
|
|
1310
|
+
if (result.success) {
|
|
1311
|
+
result.tileUrl = `${this.serverUrl}${result.tileUrl}`;
|
|
1312
|
+
}
|
|
1313
|
+
return result;
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
// ============================================
|
|
1317
|
+
// Connected accounts
|
|
1318
|
+
// ============================================
|
|
1319
|
+
|
|
1320
|
+
async getConnectedAccounts(): Promise<ConnectedAccountsResponse> {
|
|
1321
|
+
return this.jsonGet<ConnectedAccountsResponse>(
|
|
1322
|
+
"/api/v1/auth/connected-accounts",
|
|
1323
|
+
);
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
async unlinkAccount(providerId: string): Promise<UnlinkAccountResponse> {
|
|
1327
|
+
return this.jsonDelete<UnlinkAccountResponse>(
|
|
1328
|
+
`/api/v1/auth/connected-accounts/${encodeURIComponent(providerId)}`,
|
|
1329
|
+
);
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// ============================================
|
|
1333
|
+
// Stores
|
|
1334
|
+
// ============================================
|
|
1335
|
+
|
|
1336
|
+
async actionStore(options: StoreActionOptions): Promise<StoreActionResult> {
|
|
1337
|
+
const response = await this.jsonPost<
|
|
1338
|
+
| { success: true; result: JSONValue | null }
|
|
1339
|
+
| { success: false; error: string }
|
|
1340
|
+
>(
|
|
1341
|
+
`/api/v1/synced-store/instances/${encodeURIComponent(options.storeTypeId)}/${encodeURIComponent(options.instanceId)}/action`,
|
|
1342
|
+
{
|
|
1343
|
+
action_name: options.actionName,
|
|
1344
|
+
action_input: options.input,
|
|
1345
|
+
},
|
|
1346
|
+
);
|
|
1347
|
+
if (!response.success) {
|
|
1348
|
+
throw new CliError(response.error);
|
|
1349
|
+
}
|
|
1350
|
+
return {
|
|
1351
|
+
storeTypeId: options.storeTypeId,
|
|
1352
|
+
instanceId: options.instanceId,
|
|
1353
|
+
actionName: options.actionName,
|
|
1354
|
+
result: response.result,
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
async pullStore(options: StorePullOptions): Promise<StorePullResult> {
|
|
1359
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_STORE_MUTATE_TIMEOUT_MS;
|
|
1360
|
+
const clientId = `poe-tiles-cli-${createRequestId()}`;
|
|
1361
|
+
const socket = await this.openStoreSocket({
|
|
1362
|
+
clientId,
|
|
1363
|
+
timeoutMs,
|
|
1364
|
+
});
|
|
1365
|
+
try {
|
|
1366
|
+
const requestId = createRequestId();
|
|
1367
|
+
const pullResult = await sendStorePullRequest({
|
|
1368
|
+
socket,
|
|
1369
|
+
storeTypeId: options.storeTypeId,
|
|
1370
|
+
instanceId: options.instanceId,
|
|
1371
|
+
requestId,
|
|
1372
|
+
timeoutMs,
|
|
1373
|
+
request: {
|
|
1374
|
+
type: "pull_request",
|
|
1375
|
+
request_id: requestId,
|
|
1376
|
+
after_version: options.afterVersion ?? 0,
|
|
1377
|
+
target_local_bytes: options.targetLocalBytes ?? 1_000_000,
|
|
1378
|
+
},
|
|
1379
|
+
});
|
|
1380
|
+
return {
|
|
1381
|
+
storeTypeId: options.storeTypeId,
|
|
1382
|
+
instanceId: options.instanceId,
|
|
1383
|
+
requestId,
|
|
1384
|
+
patches: pullResult.patches,
|
|
1385
|
+
finalMetadata: pullResult.finalMetadata,
|
|
1386
|
+
};
|
|
1387
|
+
} finally {
|
|
1388
|
+
socket.close();
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
async getStoreItem(options: StoreGetOptions): Promise<StoreGetResult> {
|
|
1393
|
+
const response = await this.jsonPost<
|
|
1394
|
+
| {
|
|
1395
|
+
success: true;
|
|
1396
|
+
storeVersion: number;
|
|
1397
|
+
found: boolean;
|
|
1398
|
+
value: JSONValue | null;
|
|
1399
|
+
}
|
|
1400
|
+
| { success: false; error: string }
|
|
1401
|
+
>(
|
|
1402
|
+
`/api/v1/synced-store/instances/${encodeURIComponent(options.storeTypeId)}/${encodeURIComponent(options.instanceId)}/get`,
|
|
1403
|
+
{
|
|
1404
|
+
table_name: options.tableName,
|
|
1405
|
+
key: options.key,
|
|
1406
|
+
},
|
|
1407
|
+
);
|
|
1408
|
+
if (!response.success) {
|
|
1409
|
+
throw new CliError(response.error);
|
|
1410
|
+
}
|
|
1411
|
+
return {
|
|
1412
|
+
storeTypeId: options.storeTypeId,
|
|
1413
|
+
instanceId: options.instanceId,
|
|
1414
|
+
tableName: options.tableName,
|
|
1415
|
+
key: options.key,
|
|
1416
|
+
storeVersion: response.storeVersion,
|
|
1417
|
+
found: response.found,
|
|
1418
|
+
value: response.value,
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
async scanStore(options: StoreScanOptions): Promise<StoreScanResult> {
|
|
1423
|
+
const response = await this.jsonPost<
|
|
1424
|
+
| {
|
|
1425
|
+
success: true;
|
|
1426
|
+
storeVersion: number;
|
|
1427
|
+
items: StoreReadItem[];
|
|
1428
|
+
truncated: boolean;
|
|
1429
|
+
nextCursor?: { sortKey?: string; itemKey: string };
|
|
1430
|
+
}
|
|
1431
|
+
| { success: false; error: string }
|
|
1432
|
+
>(
|
|
1433
|
+
`/api/v1/synced-store/instances/${encodeURIComponent(options.storeTypeId)}/${encodeURIComponent(options.instanceId)}/scan`,
|
|
1434
|
+
{
|
|
1435
|
+
table_name: options.tableName,
|
|
1436
|
+
...(options.prefix !== undefined
|
|
1437
|
+
? { prefix: options.prefix }
|
|
1438
|
+
: undefined),
|
|
1439
|
+
...(options.cursor !== undefined
|
|
1440
|
+
? { cursor: options.cursor }
|
|
1441
|
+
: undefined),
|
|
1442
|
+
...(options.limit !== undefined ? { limit: options.limit } : undefined),
|
|
1443
|
+
...(options.reverse === true ? { reverse: true } : undefined),
|
|
1444
|
+
},
|
|
1445
|
+
);
|
|
1446
|
+
if (!response.success) {
|
|
1447
|
+
throw new CliError(response.error);
|
|
1448
|
+
}
|
|
1449
|
+
return {
|
|
1450
|
+
storeTypeId: options.storeTypeId,
|
|
1451
|
+
instanceId: options.instanceId,
|
|
1452
|
+
tableName: options.tableName,
|
|
1453
|
+
storeVersion: response.storeVersion,
|
|
1454
|
+
items: response.items,
|
|
1455
|
+
truncated: response.truncated,
|
|
1456
|
+
...(response.nextCursor !== undefined
|
|
1457
|
+
? { nextCursor: response.nextCursor }
|
|
1458
|
+
: undefined),
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
async mutateStore(options: StoreMutateOptions): Promise<StoreMutateResult> {
|
|
1463
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_STORE_MUTATE_TIMEOUT_MS;
|
|
1464
|
+
const clientId = `poe-tiles-cli-${createRequestId()}`;
|
|
1465
|
+
const mutationId = 1;
|
|
1466
|
+
const socket = await this.openStoreSocket({
|
|
1467
|
+
clientId,
|
|
1468
|
+
timeoutMs,
|
|
1469
|
+
});
|
|
1470
|
+
try {
|
|
1471
|
+
const schemaRequestId = createRequestId();
|
|
1472
|
+
const schemaResponse = await sendStoreRequest({
|
|
1473
|
+
isResponse: isStoreResponse,
|
|
1474
|
+
socket,
|
|
1475
|
+
storeTypeId: options.storeTypeId,
|
|
1476
|
+
instanceId: options.instanceId,
|
|
1477
|
+
requestId: schemaRequestId,
|
|
1478
|
+
timeoutMs,
|
|
1479
|
+
request: {
|
|
1480
|
+
type: "get_schema_request",
|
|
1481
|
+
request_id: schemaRequestId,
|
|
1482
|
+
},
|
|
1483
|
+
});
|
|
1484
|
+
if (schemaResponse.type !== "get_schema_response") {
|
|
1485
|
+
throw new CliError(
|
|
1486
|
+
`Expected get_schema_response, received ${schemaResponse.type}.`,
|
|
1487
|
+
);
|
|
1488
|
+
}
|
|
1489
|
+
if (!schemaResponse.success) {
|
|
1490
|
+
throw new CliError(
|
|
1491
|
+
`Schema request failed: ${schemaResponse.error.type}: ${schemaResponse.error.message}`,
|
|
1492
|
+
);
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
const requestId = createRequestId();
|
|
1496
|
+
const pushResponse = await sendStoreRequest({
|
|
1497
|
+
isResponse: isStoreResponse,
|
|
1498
|
+
socket,
|
|
1499
|
+
storeTypeId: options.storeTypeId,
|
|
1500
|
+
instanceId: options.instanceId,
|
|
1501
|
+
requestId,
|
|
1502
|
+
timeoutMs,
|
|
1503
|
+
request: {
|
|
1504
|
+
type: "push_request",
|
|
1505
|
+
request_id: requestId,
|
|
1506
|
+
mutations: [
|
|
1507
|
+
{
|
|
1508
|
+
id: mutationId,
|
|
1509
|
+
name: options.mutationName,
|
|
1510
|
+
input: options.input,
|
|
1511
|
+
schema_version: schemaResponse.result.schemaVersion,
|
|
1512
|
+
},
|
|
1513
|
+
],
|
|
1514
|
+
},
|
|
1515
|
+
});
|
|
1516
|
+
if (pushResponse.type !== "push_response") {
|
|
1517
|
+
throw new CliError(
|
|
1518
|
+
`Expected push_response, received ${pushResponse.type}.`,
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
if (!pushResponse.success) {
|
|
1522
|
+
throw new CliError(
|
|
1523
|
+
`Mutation push failed: ${pushResponse.error.type}: ${pushResponse.error.message}`,
|
|
1524
|
+
);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
return {
|
|
1528
|
+
storeTypeId: options.storeTypeId,
|
|
1529
|
+
instanceId: options.instanceId,
|
|
1530
|
+
mutationName: options.mutationName,
|
|
1531
|
+
clientId,
|
|
1532
|
+
mutationId,
|
|
1533
|
+
requestId,
|
|
1534
|
+
schemaVersion: schemaResponse.result.schemaVersion,
|
|
1535
|
+
version: pushResponse.result.version,
|
|
1536
|
+
failedMutations: pushResponse.result.failed_mutations,
|
|
1537
|
+
externalDispatchTargets:
|
|
1538
|
+
pushResponse.result.external_dispatch_targets ?? [],
|
|
1539
|
+
};
|
|
1540
|
+
} finally {
|
|
1541
|
+
socket.close();
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
async getStoreSchema(
|
|
1546
|
+
options: StoreSchemaOptions,
|
|
1547
|
+
): Promise<StoreSchemaResult> {
|
|
1548
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_STORE_MUTATE_TIMEOUT_MS;
|
|
1549
|
+
const clientId = `poe-tiles-cli-${createRequestId()}`;
|
|
1550
|
+
const socket = await this.openStoreSocket({
|
|
1551
|
+
clientId,
|
|
1552
|
+
timeoutMs,
|
|
1553
|
+
});
|
|
1554
|
+
try {
|
|
1555
|
+
const requestId = createRequestId();
|
|
1556
|
+
const schemaResponse = await sendStoreRequest({
|
|
1557
|
+
isResponse: isStoreResponse,
|
|
1558
|
+
socket,
|
|
1559
|
+
storeTypeId: options.storeTypeId,
|
|
1560
|
+
instanceId: options.instanceId,
|
|
1561
|
+
requestId,
|
|
1562
|
+
timeoutMs,
|
|
1563
|
+
request: {
|
|
1564
|
+
type: "get_schema_request",
|
|
1565
|
+
request_id: requestId,
|
|
1566
|
+
},
|
|
1567
|
+
});
|
|
1568
|
+
if (schemaResponse.type !== "get_schema_response") {
|
|
1569
|
+
throw new CliError(
|
|
1570
|
+
`Expected get_schema_response, received ${schemaResponse.type}.`,
|
|
1571
|
+
);
|
|
1572
|
+
}
|
|
1573
|
+
if (!schemaResponse.success) {
|
|
1574
|
+
throw new CliError(
|
|
1575
|
+
`Schema request failed: ${schemaResponse.error.type}: ${schemaResponse.error.message}`,
|
|
1576
|
+
);
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
return {
|
|
1580
|
+
storeTypeId: options.storeTypeId,
|
|
1581
|
+
instanceId: options.instanceId,
|
|
1582
|
+
schema: schemaResponse.result,
|
|
1583
|
+
};
|
|
1584
|
+
} finally {
|
|
1585
|
+
socket.close();
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
async checkStoreAccess(
|
|
1590
|
+
options: StoreAccessOptions,
|
|
1591
|
+
): Promise<StoreAccessResult> {
|
|
1592
|
+
const userId = await this.getCurrentUserId();
|
|
1593
|
+
if (!this.sessionCookie) {
|
|
1594
|
+
throw new CliError(
|
|
1595
|
+
"Login did not return a session cookie; cannot open store WebSocket.",
|
|
1596
|
+
);
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_STORE_MUTATE_TIMEOUT_MS;
|
|
1600
|
+
const clientId = `poe-tiles-cli-${createRequestId()}`;
|
|
1601
|
+
const socket = await this.openStoreSocket({
|
|
1602
|
+
clientId,
|
|
1603
|
+
timeoutMs,
|
|
1604
|
+
});
|
|
1605
|
+
try {
|
|
1606
|
+
const requestId = createRequestId();
|
|
1607
|
+
const pullResult = await sendStorePullRequest({
|
|
1608
|
+
socket,
|
|
1609
|
+
storeTypeId: options.storeTypeId,
|
|
1610
|
+
instanceId: options.instanceId,
|
|
1611
|
+
requestId,
|
|
1612
|
+
timeoutMs,
|
|
1613
|
+
request: {
|
|
1614
|
+
type: "pull_request",
|
|
1615
|
+
request_id: requestId,
|
|
1616
|
+
after_version: 0,
|
|
1617
|
+
target_local_bytes: 1_000_000,
|
|
1618
|
+
},
|
|
1619
|
+
});
|
|
1620
|
+
const membership = activeMembershipForUser(pullResult.patches, userId);
|
|
1621
|
+
return {
|
|
1622
|
+
storeTypeId: options.storeTypeId,
|
|
1623
|
+
instanceId: options.instanceId,
|
|
1624
|
+
userId,
|
|
1625
|
+
hasAccess: membership !== undefined,
|
|
1626
|
+
version: pullResult.finalMetadata.version,
|
|
1627
|
+
schemaVersion: pullResult.finalMetadata.schema_version,
|
|
1628
|
+
...(membership !== undefined ? { membership } : undefined),
|
|
1629
|
+
};
|
|
1630
|
+
} finally {
|
|
1631
|
+
socket.close();
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
/**
|
|
1636
|
+
* Open a WebSocket to the admin-only synced-store recorder endpoint,
|
|
1637
|
+
* streaming every span happening in the target store instance's Durable
|
|
1638
|
+
* Object until the caller closes the socket. Requires the authenticated
|
|
1639
|
+
* user's verified phone number to be on the server's admin allowlist —
|
|
1640
|
+
* non-admins get a connection failure (the WebSocket protocol can't
|
|
1641
|
+
* surface the server's 403 body; if you're not on the admin allowlist,
|
|
1642
|
+
* that's the likely cause).
|
|
1643
|
+
*/
|
|
1644
|
+
async openAdminRecorderSocket(options: {
|
|
1645
|
+
typeId: string;
|
|
1646
|
+
instanceId: string;
|
|
1647
|
+
timeoutMs: number;
|
|
1648
|
+
}): Promise<CliWebSocket> {
|
|
1649
|
+
await this.ensureLoggedIn();
|
|
1650
|
+
if (!this.sessionCookie) {
|
|
1651
|
+
throw new CliError(
|
|
1652
|
+
"Login did not return a session cookie; cannot open admin recorder WebSocket.",
|
|
1653
|
+
{ nonRetryable: true },
|
|
1654
|
+
);
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
const url = new URL("/api/v1/admin/synced-store/recorder", this.serverUrl);
|
|
1658
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1659
|
+
url.searchParams.set("typeId", options.typeId);
|
|
1660
|
+
url.searchParams.set("instanceId", options.instanceId);
|
|
1661
|
+
|
|
1662
|
+
const socket = this.webSocketFactory(url.toString(), {
|
|
1663
|
+
headers: this.authHeaders(),
|
|
1664
|
+
});
|
|
1665
|
+
|
|
1666
|
+
return new Promise<CliWebSocket>((resolve, reject) => {
|
|
1667
|
+
// biome-ignore lint: CLI WebSocket operations need a wall-clock open timeout.
|
|
1668
|
+
const timeout = setTimeout(() => {
|
|
1669
|
+
socket.close();
|
|
1670
|
+
reject(
|
|
1671
|
+
new CliError(
|
|
1672
|
+
`Timed out opening admin recorder WebSocket after ${options.timeoutMs}ms.`,
|
|
1673
|
+
),
|
|
1674
|
+
);
|
|
1675
|
+
}, options.timeoutMs);
|
|
1676
|
+
|
|
1677
|
+
socket.onopen = () => {
|
|
1678
|
+
clearTimeout(timeout);
|
|
1679
|
+
resolve(socket);
|
|
1680
|
+
};
|
|
1681
|
+
socket.onerror = () => {
|
|
1682
|
+
clearTimeout(timeout);
|
|
1683
|
+
reject(
|
|
1684
|
+
new CliError(
|
|
1685
|
+
"Admin recorder WebSocket connection failed. If your account isn't on the admin allowlist, the server rejects this connection.",
|
|
1686
|
+
),
|
|
1687
|
+
);
|
|
1688
|
+
};
|
|
1689
|
+
socket.onclose = (event) => {
|
|
1690
|
+
clearTimeout(timeout);
|
|
1691
|
+
reject(
|
|
1692
|
+
new CliError(
|
|
1693
|
+
`Admin recorder WebSocket closed before connecting (${event.code}${event.reason ? `: ${event.reason}` : ""}). If your account isn't on the admin allowlist, the server rejects this connection.`,
|
|
1694
|
+
),
|
|
1695
|
+
);
|
|
1696
|
+
};
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
// ============================================
|
|
1701
|
+
// Internal helpers
|
|
1702
|
+
// ============================================
|
|
1703
|
+
|
|
1704
|
+
private async ensureLoggedIn(): Promise<void> {
|
|
1705
|
+
if (this.sessionCookie) return;
|
|
1706
|
+
if (!this.apiKey) {
|
|
1707
|
+
throw new CliError(
|
|
1708
|
+
`No Poe Tiles session token is configured. Run \`${cliName()} login\`.`,
|
|
1709
|
+
{ nonRetryable: true },
|
|
1710
|
+
);
|
|
1711
|
+
}
|
|
1712
|
+
// A creator-scoped token cannot mint a session; requests carry it as a
|
|
1713
|
+
// Bearer header instead (see authHeaders).
|
|
1714
|
+
if (isCreatorScopedToken(this.apiKey)) return;
|
|
1715
|
+
await this.login();
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
/** The signed-in caller's platform user id (a tile's `creator_id` when they own it). */
|
|
1719
|
+
async getCurrentUserId(): Promise<string> {
|
|
1720
|
+
await this.ensureLoggedIn();
|
|
1721
|
+
if (this.currentUserId) return this.currentUserId;
|
|
1722
|
+
const session = await this.getSession();
|
|
1723
|
+
if (!session.success) {
|
|
1724
|
+
throw new CliError(session.error);
|
|
1725
|
+
}
|
|
1726
|
+
this.currentUserId = session.user.user_id;
|
|
1727
|
+
return this.currentUserId;
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
private extractSessionCookie(res: Response): void {
|
|
1731
|
+
const setCookie = res.headers.get("set-cookie");
|
|
1732
|
+
if (!setCookie) return;
|
|
1733
|
+
const match = /session_token=([^;]+)/.exec(setCookie);
|
|
1734
|
+
if (match) {
|
|
1735
|
+
this.sessionCookie = match[1];
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
private async jsonGet<T>(path: string): Promise<T> {
|
|
1740
|
+
await this.ensureLoggedIn();
|
|
1741
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
1742
|
+
headers: this.authHeaders(),
|
|
1743
|
+
});
|
|
1744
|
+
if (!res.ok) {
|
|
1745
|
+
throw await apiError({ op: "Request", res });
|
|
1746
|
+
}
|
|
1747
|
+
return res.json() as Promise<T>;
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
private async jsonPost<T>(path: string, body?: unknown): Promise<T> {
|
|
1751
|
+
await this.ensureLoggedIn();
|
|
1752
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
1753
|
+
method: "POST",
|
|
1754
|
+
headers: {
|
|
1755
|
+
...this.authHeaders(),
|
|
1756
|
+
"X-Requested-With": CSRF_REQUESTED_WITH,
|
|
1757
|
+
...(body !== undefined
|
|
1758
|
+
? { "Content-Type": "application/json" }
|
|
1759
|
+
: undefined),
|
|
1760
|
+
},
|
|
1761
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
1762
|
+
});
|
|
1763
|
+
if (!res.ok) {
|
|
1764
|
+
throw await apiError({ op: "Request", res });
|
|
1765
|
+
}
|
|
1766
|
+
return res.json() as Promise<T>;
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
private async jsonPut<T>(path: string, body?: unknown): Promise<T> {
|
|
1770
|
+
await this.ensureLoggedIn();
|
|
1771
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
1772
|
+
method: "PUT",
|
|
1773
|
+
headers: {
|
|
1774
|
+
...this.authHeaders(),
|
|
1775
|
+
"X-Requested-With": CSRF_REQUESTED_WITH,
|
|
1776
|
+
...(body !== undefined
|
|
1777
|
+
? { "Content-Type": "application/json" }
|
|
1778
|
+
: undefined),
|
|
1779
|
+
},
|
|
1780
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
1781
|
+
});
|
|
1782
|
+
if (!res.ok) {
|
|
1783
|
+
throw await apiError({ op: "Request", res });
|
|
1784
|
+
}
|
|
1785
|
+
return res.json() as Promise<T>;
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
private async jsonPatch<T>(path: string, body?: unknown): Promise<T> {
|
|
1789
|
+
await this.ensureLoggedIn();
|
|
1790
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
1791
|
+
method: "PATCH",
|
|
1792
|
+
headers: {
|
|
1793
|
+
...this.authHeaders(),
|
|
1794
|
+
"X-Requested-With": CSRF_REQUESTED_WITH,
|
|
1795
|
+
...(body !== undefined
|
|
1796
|
+
? { "Content-Type": "application/json" }
|
|
1797
|
+
: undefined),
|
|
1798
|
+
},
|
|
1799
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
1800
|
+
});
|
|
1801
|
+
if (!res.ok) {
|
|
1802
|
+
throw await apiError({ op: "Request", res });
|
|
1803
|
+
}
|
|
1804
|
+
return res.json() as Promise<T>;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
private async jsonDelete<T>(path: string): Promise<T> {
|
|
1808
|
+
await this.ensureLoggedIn();
|
|
1809
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
1810
|
+
method: "DELETE",
|
|
1811
|
+
headers: {
|
|
1812
|
+
...this.authHeaders(),
|
|
1813
|
+
"X-Requested-With": CSRF_REQUESTED_WITH,
|
|
1814
|
+
},
|
|
1815
|
+
});
|
|
1816
|
+
if (!res.ok) {
|
|
1817
|
+
throw await apiError({ op: "Request", res });
|
|
1818
|
+
}
|
|
1819
|
+
return res.json() as Promise<T>;
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
private authHeaders(): Record<string, string> {
|
|
1823
|
+
if (this.sessionCookie) {
|
|
1824
|
+
return { Cookie: `session_token=${this.sessionCookie}` };
|
|
1825
|
+
}
|
|
1826
|
+
if (this.apiKey && isCreatorScopedToken(this.apiKey)) {
|
|
1827
|
+
return { Authorization: `Bearer ${this.apiKey}` };
|
|
1828
|
+
}
|
|
1829
|
+
return {};
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
/** True when requests carry a Creator-scoped bearer, per `authHeaders`, rather than a session. */
|
|
1833
|
+
private sendsCreatorScopedBearer(): boolean {
|
|
1834
|
+
return (
|
|
1835
|
+
!this.sessionCookie &&
|
|
1836
|
+
this.apiKey !== undefined &&
|
|
1837
|
+
isCreatorScopedToken(this.apiKey)
|
|
1838
|
+
);
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
private async openStoreSocket(options: {
|
|
1842
|
+
clientId: string;
|
|
1843
|
+
timeoutMs: number;
|
|
1844
|
+
}): Promise<CliWebSocket> {
|
|
1845
|
+
await this.ensureLoggedIn();
|
|
1846
|
+
if (!this.sessionCookie) {
|
|
1847
|
+
throw new CliError(
|
|
1848
|
+
"Login did not return a session cookie; cannot open store WebSocket.",
|
|
1849
|
+
);
|
|
1850
|
+
}
|
|
1851
|
+
const url = new URL("/api/v1/user-router", this.serverUrl);
|
|
1852
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1853
|
+
url.searchParams.set("clientId", options.clientId);
|
|
1854
|
+
url.searchParams.set("library_version", String(SYNC_LIBRARY_VERSION));
|
|
1855
|
+
|
|
1856
|
+
const socket = this.webSocketFactory(url.toString(), {
|
|
1857
|
+
headers: this.authHeaders(),
|
|
1858
|
+
});
|
|
1859
|
+
|
|
1860
|
+
return new Promise<CliWebSocket>((resolve, reject) => {
|
|
1861
|
+
// biome-ignore lint: CLI WebSocket operations need a wall-clock open timeout.
|
|
1862
|
+
const timeout = setTimeout(() => {
|
|
1863
|
+
socket.close();
|
|
1864
|
+
reject(
|
|
1865
|
+
new CliError(
|
|
1866
|
+
`Timed out opening store WebSocket after ${options.timeoutMs}ms.`,
|
|
1867
|
+
),
|
|
1868
|
+
);
|
|
1869
|
+
}, options.timeoutMs);
|
|
1870
|
+
|
|
1871
|
+
socket.onopen = () => {
|
|
1872
|
+
clearTimeout(timeout);
|
|
1873
|
+
resolve(socket);
|
|
1874
|
+
};
|
|
1875
|
+
socket.onerror = () => {
|
|
1876
|
+
clearTimeout(timeout);
|
|
1877
|
+
reject(new CliError("Store WebSocket connection failed."));
|
|
1878
|
+
};
|
|
1879
|
+
socket.onclose = (event) => {
|
|
1880
|
+
clearTimeout(timeout);
|
|
1881
|
+
reject(
|
|
1882
|
+
new CliError(
|
|
1883
|
+
`Store WebSocket closed before connecting (${event.code}${event.reason ? `: ${event.reason}` : ""}).`,
|
|
1884
|
+
),
|
|
1885
|
+
);
|
|
1886
|
+
};
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
function createDefaultWebSocket(
|
|
1892
|
+
url: string,
|
|
1893
|
+
options?: WebSocketConnectOptions,
|
|
1894
|
+
): CliWebSocket {
|
|
1895
|
+
const RuntimeWebSocket = WebSocket as unknown as {
|
|
1896
|
+
new (url: string, options?: WebSocketConnectOptions): CliWebSocket;
|
|
1897
|
+
};
|
|
1898
|
+
return new RuntimeWebSocket(url, options);
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
type StoreRequest =
|
|
1902
|
+
| {
|
|
1903
|
+
type: "get_schema_request";
|
|
1904
|
+
request_id: string;
|
|
1905
|
+
}
|
|
1906
|
+
| {
|
|
1907
|
+
type: "pull_request";
|
|
1908
|
+
request_id: string;
|
|
1909
|
+
after_version?: number;
|
|
1910
|
+
target_local_bytes: number;
|
|
1911
|
+
}
|
|
1912
|
+
| {
|
|
1913
|
+
type: "push_request";
|
|
1914
|
+
request_id: string;
|
|
1915
|
+
mutations: Array<{
|
|
1916
|
+
id: number;
|
|
1917
|
+
name: string;
|
|
1918
|
+
input: JSONValue;
|
|
1919
|
+
schema_version: number;
|
|
1920
|
+
}>;
|
|
1921
|
+
};
|
|
1922
|
+
|
|
1923
|
+
type StoreResponse =
|
|
1924
|
+
| {
|
|
1925
|
+
type: "get_schema_response";
|
|
1926
|
+
success: true;
|
|
1927
|
+
request_id: string;
|
|
1928
|
+
result: StoreSchemaInfo;
|
|
1929
|
+
}
|
|
1930
|
+
| {
|
|
1931
|
+
type: "get_schema_response";
|
|
1932
|
+
success: false;
|
|
1933
|
+
request_id: string;
|
|
1934
|
+
error: { type: string; message: string; stack_trace?: string };
|
|
1935
|
+
}
|
|
1936
|
+
| {
|
|
1937
|
+
type: "push_response";
|
|
1938
|
+
success: true;
|
|
1939
|
+
request_id: string;
|
|
1940
|
+
result: {
|
|
1941
|
+
version: number;
|
|
1942
|
+
failed_mutations: FailedMutationInfo[];
|
|
1943
|
+
external_dispatch_targets?: ExternalDispatchTarget[];
|
|
1944
|
+
};
|
|
1945
|
+
}
|
|
1946
|
+
| {
|
|
1947
|
+
type: "push_response";
|
|
1948
|
+
success: false;
|
|
1949
|
+
request_id: string;
|
|
1950
|
+
error: { type: string; message: string; stack_trace?: string };
|
|
1951
|
+
};
|
|
1952
|
+
|
|
1953
|
+
export type PullPatch =
|
|
1954
|
+
| {
|
|
1955
|
+
op: "set";
|
|
1956
|
+
sortKey?: string;
|
|
1957
|
+
tableName: string;
|
|
1958
|
+
itemKey: string;
|
|
1959
|
+
value: JSONValue;
|
|
1960
|
+
}
|
|
1961
|
+
| {
|
|
1962
|
+
op: "del";
|
|
1963
|
+
sortKey?: string;
|
|
1964
|
+
tableName: string;
|
|
1965
|
+
itemKey: string;
|
|
1966
|
+
};
|
|
1967
|
+
|
|
1968
|
+
export interface PullFinalMetadata {
|
|
1969
|
+
version: number;
|
|
1970
|
+
last_mutation_id: number;
|
|
1971
|
+
client_info: {
|
|
1972
|
+
client_id: string;
|
|
1973
|
+
user_id: string;
|
|
1974
|
+
library_version: number;
|
|
1975
|
+
client_ordinal?: number;
|
|
1976
|
+
};
|
|
1977
|
+
schema_version: number;
|
|
1978
|
+
requires_full_resync: boolean;
|
|
1979
|
+
total_bytes: number;
|
|
1980
|
+
clear_external_source_keys?: string[];
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
interface PullResponseChunk {
|
|
1984
|
+
type: "pull_response_chunk";
|
|
1985
|
+
request_id: string;
|
|
1986
|
+
window_index: number;
|
|
1987
|
+
patches: PullPatch[];
|
|
1988
|
+
sort_key_range: { start: string; end: string };
|
|
1989
|
+
more_data_available?: boolean;
|
|
1990
|
+
more_older_data_available?: boolean;
|
|
1991
|
+
more_newer_data_available?: boolean;
|
|
1992
|
+
final_metadata?: PullFinalMetadata;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
interface PullStreamError {
|
|
1996
|
+
type: "pull_stream_error";
|
|
1997
|
+
request_id: string;
|
|
1998
|
+
window_index?: number;
|
|
1999
|
+
error: { type: string; message: string; stack_trace?: string };
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
interface StorePullTransportResult {
|
|
2003
|
+
patches: PullPatch[];
|
|
2004
|
+
finalMetadata: PullFinalMetadata;
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
async function sendStorePullRequest(options: {
|
|
2008
|
+
socket: CliWebSocket;
|
|
2009
|
+
storeTypeId: string;
|
|
2010
|
+
instanceId: string;
|
|
2011
|
+
requestId: string;
|
|
2012
|
+
timeoutMs: number;
|
|
2013
|
+
request: Extract<StoreRequest, { type: "pull_request" }>;
|
|
2014
|
+
}): Promise<StorePullTransportResult> {
|
|
2015
|
+
const { socket, storeTypeId, instanceId, requestId, timeoutMs, request } =
|
|
2016
|
+
options;
|
|
2017
|
+
|
|
2018
|
+
return new Promise<StorePullTransportResult>((resolve, reject) => {
|
|
2019
|
+
const previousOnMessage = socket.onmessage;
|
|
2020
|
+
const previousOnClose = socket.onclose;
|
|
2021
|
+
const previousOnError = socket.onerror;
|
|
2022
|
+
const patches: PullPatch[] = [];
|
|
2023
|
+
|
|
2024
|
+
const cleanup = () => {
|
|
2025
|
+
clearTimeout(timeout);
|
|
2026
|
+
socket.onmessage = previousOnMessage;
|
|
2027
|
+
socket.onclose = previousOnClose;
|
|
2028
|
+
socket.onerror = previousOnError;
|
|
2029
|
+
};
|
|
2030
|
+
|
|
2031
|
+
// biome-ignore lint: CLI WebSocket operations need a wall-clock pull timeout.
|
|
2032
|
+
const timeout = setTimeout(() => {
|
|
2033
|
+
cleanup();
|
|
2034
|
+
reject(
|
|
2035
|
+
new CliError(`Timed out waiting for store pull after ${timeoutMs}ms.`),
|
|
2036
|
+
);
|
|
2037
|
+
}, timeoutMs);
|
|
2038
|
+
|
|
2039
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Existing function exceeds the cognitive-complexity limit; keep the rule enabled for new code.
|
|
2040
|
+
socket.onmessage = (event) => {
|
|
2041
|
+
const data = event.data;
|
|
2042
|
+
if (typeof data !== "string") return;
|
|
2043
|
+
let parsedEnvelope: ParsedStoreEnvelope;
|
|
2044
|
+
try {
|
|
2045
|
+
parsedEnvelope = parseStoreEnvelope(data);
|
|
2046
|
+
} catch (error) {
|
|
2047
|
+
cleanup();
|
|
2048
|
+
reject(error);
|
|
2049
|
+
return;
|
|
2050
|
+
}
|
|
2051
|
+
if (
|
|
2052
|
+
parsedEnvelope.storeTypeId !== storeTypeId ||
|
|
2053
|
+
parsedEnvelope.instanceId !== instanceId
|
|
2054
|
+
) {
|
|
2055
|
+
return;
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
const parsedMessage = parseJson(parsedEnvelope.message);
|
|
2059
|
+
if (isPullStreamError(parsedMessage)) {
|
|
2060
|
+
if (parsedMessage.request_id !== requestId) return;
|
|
2061
|
+
cleanup();
|
|
2062
|
+
reject(
|
|
2063
|
+
new CliError(
|
|
2064
|
+
`Store pull failed: ${parsedMessage.error.type}: ${parsedMessage.error.message}`,
|
|
2065
|
+
),
|
|
2066
|
+
);
|
|
2067
|
+
return;
|
|
2068
|
+
}
|
|
2069
|
+
if (!isPullResponseChunk(parsedMessage)) return;
|
|
2070
|
+
if (parsedMessage.request_id !== requestId) return;
|
|
2071
|
+
patches.push(...parsedMessage.patches);
|
|
2072
|
+
if (!parsedMessage.final_metadata) return;
|
|
2073
|
+
|
|
2074
|
+
cleanup();
|
|
2075
|
+
resolve({
|
|
2076
|
+
patches,
|
|
2077
|
+
finalMetadata: parsedMessage.final_metadata,
|
|
2078
|
+
});
|
|
2079
|
+
};
|
|
2080
|
+
socket.onclose = (event) => {
|
|
2081
|
+
cleanup();
|
|
2082
|
+
reject(
|
|
2083
|
+
new CliError(
|
|
2084
|
+
`Store WebSocket closed before pull response (${event.code}${event.reason ? `: ${event.reason}` : ""}).`,
|
|
2085
|
+
),
|
|
2086
|
+
);
|
|
2087
|
+
};
|
|
2088
|
+
socket.onerror = () => {
|
|
2089
|
+
cleanup();
|
|
2090
|
+
reject(new CliError("Store WebSocket failed before pull response."));
|
|
2091
|
+
};
|
|
2092
|
+
|
|
2093
|
+
socket.send(
|
|
2094
|
+
serializeStoreEnvelope(storeTypeId, instanceId, JSON.stringify(request)),
|
|
2095
|
+
);
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Existing function exceeds the cognitive-complexity limit; keep the rule enabled for new code.
|
|
2100
|
+
function isStoreResponse(value: unknown): value is StoreResponse {
|
|
2101
|
+
if (!isRecord(value)) return false;
|
|
2102
|
+
if (
|
|
2103
|
+
value["type"] !== "get_schema_response" &&
|
|
2104
|
+
value["type"] !== "push_response"
|
|
2105
|
+
) {
|
|
2106
|
+
return false;
|
|
2107
|
+
}
|
|
2108
|
+
if (typeof value["request_id"] !== "string") return false;
|
|
2109
|
+
if (typeof value["success"] !== "boolean") return false;
|
|
2110
|
+
if (value["success"]) {
|
|
2111
|
+
if (!isRecord(value["result"])) return false;
|
|
2112
|
+
if (value["type"] === "get_schema_response") {
|
|
2113
|
+
return isStoreSchemaInfo(value["result"]);
|
|
2114
|
+
}
|
|
2115
|
+
return (
|
|
2116
|
+
typeof value["result"]["version"] === "number" &&
|
|
2117
|
+
Array.isArray(value["result"]["failed_mutations"]) &&
|
|
2118
|
+
value["result"]["failed_mutations"].every(isFailedMutationInfo) &&
|
|
2119
|
+
(value["result"]["external_dispatch_targets"] === undefined ||
|
|
2120
|
+
(Array.isArray(value["result"]["external_dispatch_targets"]) &&
|
|
2121
|
+
value["result"]["external_dispatch_targets"].every(
|
|
2122
|
+
isExternalDispatchTarget,
|
|
2123
|
+
)))
|
|
2124
|
+
);
|
|
2125
|
+
}
|
|
2126
|
+
const error = value["error"];
|
|
2127
|
+
return (
|
|
2128
|
+
isRecord(error) &&
|
|
2129
|
+
typeof error["type"] === "string" &&
|
|
2130
|
+
typeof error["message"] === "string"
|
|
2131
|
+
);
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
function isStoreSchemaInfo(value: unknown): value is StoreSchemaInfo {
|
|
2135
|
+
if (!isRecord(value)) return false;
|
|
2136
|
+
return (
|
|
2137
|
+
typeof value["type"] === "string" &&
|
|
2138
|
+
typeof value["schemaVersion"] === "number" &&
|
|
2139
|
+
isRecord(value["tables"]) &&
|
|
2140
|
+
Array.isArray(value["mutators"]) &&
|
|
2141
|
+
value["mutators"].every(isStoreMutatorSchemaInfo) &&
|
|
2142
|
+
Array.isArray(value["actions"]) &&
|
|
2143
|
+
value["actions"].every(isStoreActionSchemaInfo)
|
|
2144
|
+
);
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
function isStoreMutatorSchemaInfo(
|
|
2148
|
+
value: unknown,
|
|
2149
|
+
): value is StoreMutatorSchemaInfo {
|
|
2150
|
+
return (
|
|
2151
|
+
isRecord(value) &&
|
|
2152
|
+
typeof value["name"] === "string" &&
|
|
2153
|
+
(value["description"] === undefined ||
|
|
2154
|
+
typeof value["description"] === "string") &&
|
|
2155
|
+
isRecord(value["inputSchema"])
|
|
2156
|
+
);
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
function isStoreActionSchemaInfo(
|
|
2160
|
+
value: unknown,
|
|
2161
|
+
): value is StoreActionSchemaInfo {
|
|
2162
|
+
return (
|
|
2163
|
+
isRecord(value) &&
|
|
2164
|
+
typeof value["name"] === "string" &&
|
|
2165
|
+
(value["description"] === undefined ||
|
|
2166
|
+
typeof value["description"] === "string") &&
|
|
2167
|
+
isRecord(value["inputSchema"]) &&
|
|
2168
|
+
isRecord(value["outputSchema"])
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
function isPullResponseChunk(value: unknown): value is PullResponseChunk {
|
|
2173
|
+
return (
|
|
2174
|
+
isRecord(value) &&
|
|
2175
|
+
value["type"] === "pull_response_chunk" &&
|
|
2176
|
+
typeof value["request_id"] === "string" &&
|
|
2177
|
+
typeof value["window_index"] === "number" &&
|
|
2178
|
+
Array.isArray(value["patches"]) &&
|
|
2179
|
+
value["patches"].every(isPullPatch) &&
|
|
2180
|
+
isSortKeyRange(value["sort_key_range"]) &&
|
|
2181
|
+
(value["final_metadata"] === undefined ||
|
|
2182
|
+
isPullFinalMetadata(value["final_metadata"]))
|
|
2183
|
+
);
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
function isPullStreamError(value: unknown): value is PullStreamError {
|
|
2187
|
+
return (
|
|
2188
|
+
isRecord(value) &&
|
|
2189
|
+
value["type"] === "pull_stream_error" &&
|
|
2190
|
+
typeof value["request_id"] === "string" &&
|
|
2191
|
+
(value["window_index"] === undefined ||
|
|
2192
|
+
typeof value["window_index"] === "number") &&
|
|
2193
|
+
isRecord(value["error"]) &&
|
|
2194
|
+
typeof value["error"]["type"] === "string" &&
|
|
2195
|
+
typeof value["error"]["message"] === "string"
|
|
2196
|
+
);
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
function isPullPatch(value: unknown): value is PullPatch {
|
|
2200
|
+
if (!isRecord(value)) return false;
|
|
2201
|
+
if (
|
|
2202
|
+
(value["op"] !== "set" && value["op"] !== "del") ||
|
|
2203
|
+
(value["sortKey"] !== undefined && typeof value["sortKey"] !== "string") ||
|
|
2204
|
+
typeof value["tableName"] !== "string" ||
|
|
2205
|
+
typeof value["itemKey"] !== "string"
|
|
2206
|
+
) {
|
|
2207
|
+
return false;
|
|
2208
|
+
}
|
|
2209
|
+
return value["op"] === "del" || isJsonValue(value["value"]);
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
function isSortKeyRange(
|
|
2213
|
+
value: unknown,
|
|
2214
|
+
): value is { start: string; end: string } {
|
|
2215
|
+
return (
|
|
2216
|
+
isRecord(value) &&
|
|
2217
|
+
typeof value["start"] === "string" &&
|
|
2218
|
+
typeof value["end"] === "string"
|
|
2219
|
+
);
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
function isPullFinalMetadata(value: unknown): value is PullFinalMetadata {
|
|
2223
|
+
return (
|
|
2224
|
+
isRecord(value) &&
|
|
2225
|
+
typeof value["version"] === "number" &&
|
|
2226
|
+
typeof value["last_mutation_id"] === "number" &&
|
|
2227
|
+
isRecord(value["client_info"]) &&
|
|
2228
|
+
typeof value["client_info"]["client_id"] === "string" &&
|
|
2229
|
+
typeof value["client_info"]["user_id"] === "string" &&
|
|
2230
|
+
typeof value["client_info"]["library_version"] === "number" &&
|
|
2231
|
+
(value["client_info"]["client_ordinal"] === undefined ||
|
|
2232
|
+
typeof value["client_info"]["client_ordinal"] === "number") &&
|
|
2233
|
+
typeof value["schema_version"] === "number" &&
|
|
2234
|
+
typeof value["requires_full_resync"] === "boolean" &&
|
|
2235
|
+
typeof value["total_bytes"] === "number" &&
|
|
2236
|
+
(value["clear_external_source_keys"] === undefined ||
|
|
2237
|
+
(Array.isArray(value["clear_external_source_keys"]) &&
|
|
2238
|
+
value["clear_external_source_keys"].every(
|
|
2239
|
+
(key) => typeof key === "string",
|
|
2240
|
+
)))
|
|
2241
|
+
);
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
function isFailedMutationInfo(value: unknown): value is FailedMutationInfo {
|
|
2245
|
+
return (
|
|
2246
|
+
isRecord(value) &&
|
|
2247
|
+
typeof value["mutation_id"] === "number" &&
|
|
2248
|
+
typeof value["error_type"] === "string" &&
|
|
2249
|
+
typeof value["error_message"] === "string" &&
|
|
2250
|
+
typeof value["can_retry"] === "boolean" &&
|
|
2251
|
+
(value["stack_trace"] === undefined ||
|
|
2252
|
+
typeof value["stack_trace"] === "string")
|
|
2253
|
+
);
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
function isExternalDispatchTarget(
|
|
2257
|
+
value: unknown,
|
|
2258
|
+
): value is ExternalDispatchTarget {
|
|
2259
|
+
return (
|
|
2260
|
+
isRecord(value) &&
|
|
2261
|
+
typeof value["targetStoreTypeId"] === "string" &&
|
|
2262
|
+
typeof value["targetInstanceId"] === "string" &&
|
|
2263
|
+
typeof value["sourceKey"] === "string"
|
|
2264
|
+
);
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2268
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
function isJsonValue(value: unknown): value is JSONValue {
|
|
2272
|
+
if (value === null) return true;
|
|
2273
|
+
if (typeof value === "string" || typeof value === "boolean") return true;
|
|
2274
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
2275
|
+
if (Array.isArray(value)) return value.every(isJsonValue);
|
|
2276
|
+
if (!isRecord(value)) return false;
|
|
2277
|
+
return Object.values(value).every(isJsonValue);
|
|
2278
|
+
}
|
|
2279
|
+
|
|
2280
|
+
function activeMembershipForUser(
|
|
2281
|
+
patches: PullPatch[],
|
|
2282
|
+
userId: string,
|
|
2283
|
+
): JSONValue | undefined {
|
|
2284
|
+
let membership: JSONValue | undefined;
|
|
2285
|
+
for (const patch of patches) {
|
|
2286
|
+
if (patch.tableName !== "$users" || patch.itemKey !== userId) continue;
|
|
2287
|
+
if (patch.op === "del") {
|
|
2288
|
+
membership = undefined;
|
|
2289
|
+
continue;
|
|
2290
|
+
}
|
|
2291
|
+
membership = patch.value;
|
|
2292
|
+
}
|
|
2293
|
+
if (!isRecord(membership) || membership["removedAt"] !== undefined) {
|
|
2294
|
+
return undefined;
|
|
2295
|
+
}
|
|
2296
|
+
return membership;
|
|
2297
|
+
}
|
|
2298
|
+
|
|
2299
|
+
function createRequestId(): string {
|
|
2300
|
+
return crypto.randomUUID();
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
function parseDeviceCodeStart(value: unknown): DeviceCodeStartResult {
|
|
2304
|
+
if (!isRecord(value)) {
|
|
2305
|
+
throw new CliError("Device-code start returned a non-object response.");
|
|
2306
|
+
}
|
|
2307
|
+
const deviceCode = stringField(value, "device_code");
|
|
2308
|
+
const userCode = stringField(value, "user_code");
|
|
2309
|
+
const verificationUri = stringField(value, "verification_uri");
|
|
2310
|
+
const expiresIn = positiveNumberField(value, "expires_in");
|
|
2311
|
+
const interval = positiveNumberField(value, "interval");
|
|
2312
|
+
const complete = value["verification_uri_complete"];
|
|
2313
|
+
return {
|
|
2314
|
+
deviceCode,
|
|
2315
|
+
userCode,
|
|
2316
|
+
verificationUri,
|
|
2317
|
+
expiresIn,
|
|
2318
|
+
interval,
|
|
2319
|
+
...(typeof complete === "string" && complete.length > 0
|
|
2320
|
+
? { verificationUriComplete: complete }
|
|
2321
|
+
: undefined),
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
function parseDeviceCodePoll(value: unknown): DeviceCodePollResult {
|
|
2326
|
+
if (!isRecord(value)) {
|
|
2327
|
+
throw new CliError("Device-code poll returned a non-object response.");
|
|
2328
|
+
}
|
|
2329
|
+
const rawStatus =
|
|
2330
|
+
typeof value["status"] === "string"
|
|
2331
|
+
? value["status"]
|
|
2332
|
+
: typeof value["error"] === "string"
|
|
2333
|
+
? value["error"]
|
|
2334
|
+
: "";
|
|
2335
|
+
const status = normalizeDeviceCodeStatus(rawStatus);
|
|
2336
|
+
if (status === "authorized") {
|
|
2337
|
+
const user = value["user"];
|
|
2338
|
+
if (!isRecord(user)) {
|
|
2339
|
+
throw new CliError("Device-code poll response missing user.");
|
|
2340
|
+
}
|
|
2341
|
+
return {
|
|
2342
|
+
status,
|
|
2343
|
+
sessionToken: stringField(value, "session_token"),
|
|
2344
|
+
user: user as DeviceCodeLoginUser,
|
|
2345
|
+
};
|
|
2346
|
+
}
|
|
2347
|
+
return { status };
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
function normalizeDeviceCodeStatus(
|
|
2351
|
+
status: string,
|
|
2352
|
+
): DeviceCodePollResult["status"] {
|
|
2353
|
+
switch (status) {
|
|
2354
|
+
case "authorized":
|
|
2355
|
+
case "success":
|
|
2356
|
+
return "authorized";
|
|
2357
|
+
case "pending":
|
|
2358
|
+
case "authorization_pending":
|
|
2359
|
+
return "pending";
|
|
2360
|
+
case "slow_down":
|
|
2361
|
+
return "slow_down";
|
|
2362
|
+
case "expired":
|
|
2363
|
+
case "expired_token":
|
|
2364
|
+
return "expired";
|
|
2365
|
+
case "consumed":
|
|
2366
|
+
return "consumed";
|
|
2367
|
+
case "denied":
|
|
2368
|
+
case "access_denied":
|
|
2369
|
+
return "denied";
|
|
2370
|
+
default:
|
|
2371
|
+
throw new CliError(`Unexpected device-code poll status: ${status}`);
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
function stringField(value: Record<string, unknown>, field: string): string {
|
|
2376
|
+
const raw = value[field];
|
|
2377
|
+
if (typeof raw !== "string" || raw.length === 0) {
|
|
2378
|
+
throw new CliError(`Device-code response missing ${field}.`);
|
|
2379
|
+
}
|
|
2380
|
+
return raw;
|
|
2381
|
+
}
|
|
2382
|
+
|
|
2383
|
+
function positiveNumberField(
|
|
2384
|
+
value: Record<string, unknown>,
|
|
2385
|
+
field: string,
|
|
2386
|
+
): number {
|
|
2387
|
+
const raw = value[field];
|
|
2388
|
+
if (typeof raw !== "number" || raw <= 0 || !Number.isFinite(raw)) {
|
|
2389
|
+
throw new CliError(`Device-code response missing ${field}.`);
|
|
2390
|
+
}
|
|
2391
|
+
return raw;
|
|
2392
|
+
}
|
|
2393
|
+
|
|
2394
|
+
async function apiError(options: {
|
|
2395
|
+
op:
|
|
2396
|
+
| "Login"
|
|
2397
|
+
| "Device-code login"
|
|
2398
|
+
| "Device-code poll"
|
|
2399
|
+
| "Publish"
|
|
2400
|
+
| "Request";
|
|
2401
|
+
res: Response;
|
|
2402
|
+
}): Promise<CliError> {
|
|
2403
|
+
const text = await options.res.text();
|
|
2404
|
+
const message = apiErrorMessage({ text, res: options.res });
|
|
2405
|
+
return new CliError(
|
|
2406
|
+
`${options.op} failed (${options.res.status}): ${message}`,
|
|
2407
|
+
{ status: options.res.status },
|
|
2408
|
+
);
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
function apiErrorMessage(options: { text: string; res: Response }): string {
|
|
2412
|
+
const parsed = parseJson(options.text);
|
|
2413
|
+
if (isApiErrorEnvelope(parsed)) {
|
|
2414
|
+
const error = parsed.error;
|
|
2415
|
+
if (typeof error === "string") {
|
|
2416
|
+
return (
|
|
2417
|
+
nestedPoeApiErrorMessage({
|
|
2418
|
+
message: error,
|
|
2419
|
+
fallbackMessage: statusMessage(options.res),
|
|
2420
|
+
}) ?? error
|
|
2421
|
+
);
|
|
2422
|
+
}
|
|
2423
|
+
const message = errorObjectMessage(error);
|
|
2424
|
+
if (message) {
|
|
2425
|
+
return message;
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
if (options.text.trimStart().startsWith("<")) {
|
|
2430
|
+
return statusMessage(options.res);
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
return options.text;
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
function nestedPoeApiErrorMessage(options: {
|
|
2437
|
+
message: string;
|
|
2438
|
+
fallbackMessage: string;
|
|
2439
|
+
}): string | undefined {
|
|
2440
|
+
const match = /^Poe API error: \d+ - (.+)$/s.exec(options.message);
|
|
2441
|
+
if (!match) return undefined;
|
|
2442
|
+
const innerText = match[1]!;
|
|
2443
|
+
const parsed = parseJson(innerText);
|
|
2444
|
+
if (!isApiErrorEnvelope(parsed)) {
|
|
2445
|
+
return options.fallbackMessage;
|
|
2446
|
+
}
|
|
2447
|
+
return errorObjectMessage(parsed.error) ?? options.fallbackMessage;
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
function parseJson(text: string): unknown {
|
|
2451
|
+
try {
|
|
2452
|
+
return JSON.parse(text);
|
|
2453
|
+
} catch {
|
|
2454
|
+
return undefined;
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
function isApiErrorEnvelope(value: unknown): value is { error?: unknown } {
|
|
2459
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
function errorObjectMessage(value: unknown): string | undefined {
|
|
2463
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
2464
|
+
return undefined;
|
|
2465
|
+
}
|
|
2466
|
+
const error = value as { message?: unknown };
|
|
2467
|
+
return typeof error.message === "string" ? error.message : undefined;
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
function statusMessage(res: Response): string {
|
|
2471
|
+
return res.statusText
|
|
2472
|
+
? `${res.status} ${res.statusText}`
|
|
2473
|
+
: String(res.status);
|
|
2474
|
+
}
|