@qmuse/cloud-client
v1.0.9
Published
Narrow HTTP-style client for the single QMuse Cloud API Function
Maintainers
Keywords
Readme
@qmuse/cloud-client
云函数调用监控请读 雨燕监控接入与字段契约:包含预览/发布环境、请求耗时、成功率、脱敏出入参及版本与链路关联。Web 默认上报到雨燕监控项 9901,可通过 monitoring: false 关闭;小程序需显式配置 reporter。使用前需确认雨燕监控配置已发布。
用户名密码登录请先读 认证接入契约与完整示例:包含输入字段、用户返回值、恢复会话、注册后登录和退出。
异步长任务请读 提交、续查与结果确认契约:包括账号绑定、原业务键重试和回执丢失恢复。使用已发布且包含 jobs.start/get 的 SDK 版本,并搭配支持预期账号校验的 Function 认证 helper;现有应用需分别核对安装包和已部署 helper。
下方 SDK 示例使用宿主已初始化的客户端;QMuse 生成项目通过 src/services/cloud 接入,项目接入说明由 CLI 同步此认证契约。
Unified Web/PC/mini-program client for QMuse Cloud services. Business APIs use
the single qmuse-cloud-api AppBase Function. File policy uses that Function as
its control plane while large file bytes use a platform-specific Storage data
plane inside this package.
The package intentionally does not expose AppBase clients, Functions, Storage,
TablesDB, endpoint, project ID, database ID, bucket ID, permissions, or a
platform-injection API to business modules. Platform implementations are fixed
by the /web and /miniapp package entry points.
The host initializes one client for the current JavaScript runtime before mounting the application. Web and mini-program hosts may load the public connection config differently while business modules always read the same singleton:
import { getQMuseClient } from '@qmuse/cloud-client';
import { initQMuseCloudClient } from '@qmuse/cloud-client/web';
await initQMuseCloudClient({
config: () => hostRuntime.appwrite,
});
const result = await getQMuseClient().request<{ data: Order }>({
method: 'GET',
path: '/api/orders/order_1',
});initQMuseCloudClient accepts a config object or a sync/async config loader. Calls
with the same normalized endpoint, projectId, and functionId are
idempotent and concurrent calls share the same initialization. Reinitializing
with different connection config is rejected.
Each generated application owns its own AppBase users, Sessions, roles and policies. The AppBase Session is the only application login state. It supplies Function runtime identity headers and Storage permissions; there is no second application access/refresh-token layer.
The selected package entry point supplies the AppBase Account capability. Login receives a
short-lived custom-token secret from the Function and exchanges it immediately;
the secret is never returned from login, persisted, logged or put in business
state.
import { getQMuseClient } from '@qmuse/cloud-client';
const cloudClient = getQMuseClient();
await cloudClient.auth.login({ username, password });
const currentUser = await cloudClient.auth.getCurrentUser();
await cloudClient.auth.logout();
// Or revoke every AppBase Session for this user:
await cloudClient.auth.logoutAll();The mini-program entry can acquire the platform authorization code and complete Alipay login without exposing provider details to business code:
import { initQMuseCloudClient } from '@qmuse/cloud-client/miniapp';
const cloudClient = await initQMuseCloudClient({
config: () => getMuseRuntime().appwrite,
});
await cloudClient.auth.loginWithMiniapp();On Alipay this calls my.getAuthCode({ scopes: ['auth_user'] }), invokes the
dedicated /api/auth/alipay/mini/login Function route, and immediately exchanges the
returned custom token for the normal AppBase Session. On WeChat it calls
Taro.login(), sends the code to /api/auth/wechat/mini/login, and exchanges
the same kind of custom token for an AppBase Session. A caller that already has
an authorization code may use
loginWithProvider({ provider: 'alipay' | 'wechat', authCode }). Non-mini-program environments fail with
AUTH_PLATFORM_UNSUPPORTED.
register creates the user without changing the current Session. login
exchanges the custom token internally. Session refresh is single-flight and is
performed before business requests when expiry is within five minutes. Web
hosts use AppBase's secure cookie; mini-program hosts persist AppBase fallback
Session headers in storage scoped by endpoint and project ID.
Current users include id, username, role and avatarUrl. A valid HTTPS
prefs.avatarUrl is used when present; otherwise the account ID selects one of
seven fixed default avatars with FNV-1a (32-bit, UTF-16 code units). Older cloud
responses without an avatar remain supported.
Upload a custom avatar and then update the current user:
const avatar = await cloudClient.files.upload({ resource: 'user-avatar', file });
const user = await cloudClient.auth.setAvatar({ fileId: avatar.id });
image.src = user.avatarUrl;The user-avatar resource accepts JPEG, PNG and WebP up to 5 MiB. Avatars are
public images. The authenticated Function verifies ownership and a completed
upload, then saves a stable public HTTPS URL in account prefs while preserving
other preferences. Only successful updates replace the cached current user;
failed updates leave it unchanged. Replaced files are not automatically deleted.
There is no avatar-clear operation.
Existing Functions must be updated to include PUT /api/user/avatar and the
user-avatar file policy before enabling this UI. CLI upgrades preserve
create-once authentication and file sources. Missing update routes fail explicitly;
the client does not fall back to writing prefs directly.
Business file operations use a logical resource, never a bucket ID:
const attachment = await cloudClient.files.upload({
resource: 'order-attachment',
file,
relation: { orderId },
onProgress: progress => console.log(progress.progress),
});
const preview = await cloudClient.files.createPreview({
fileId: attachment.id,
width: 640,
});
image.src = preview.url;
preview.dispose();On Web, pass name when uploading a Blob, for example
cloudClient.files.upload({ resource: 'public-file', file: blob, name: 'image.png' }).
The name is used for both the upload intent and every multipart chunk. For a
File, its original name is used unless name is provided.
The upload flow creates an intent through qmuse-cloud-api, uploads in 5 MiB
chunks through the injected Web or mini-program data-plane transport, then
completes the intent through the Function. Failures preserve the original upload
reference and never automatically cancel or retransmit the file. The file
recovery API provides onUploadState, prepareUpload, completeUpload and explicit
cancelUpload; see file recovery. An intent expiry does not
schedule physical file cleanup. Preview/download access is
authorized by the Function and may return a short-lived File Token URL or an
authenticated URL that the Web transport converts to a disposable Blob URL.
The client intentionally exposes no file-list API; applications keep the file
IDs they attach to their own business records.
Initialization is available only from platform-specific entry points:
// Web build
import { initQMuseCloudClient } from '@qmuse/cloud-client/web';
await initQMuseCloudClient({
config: () => window.__MUSE__.appwrite,
});
// Taro mini-program build
import { initQMuseCloudClient } from '@qmuse/cloud-client/miniapp';
await initQMuseCloudClient({
config: () => getMuseRuntime().appwrite,
});The Web entry owns the Appwrite Web SDK and secure-cookie Session. The miniapp
entry owns Taro request, upload, storage, file-system and project-isolated
X-Fallback-Cookies Session handling. Both entries include the proven file
mechanics from the legacy @qmuse/appwrite implementation: Web File/Blob, Taro-style local paths, 5 MiB chunks,
Content-Range, X-Appwrite-ID continuation, progress, fallback Session
headers and mini-program temporary-file cleanup. They do not migrate TablesDB
CRUD or the legacy anonymous Role.any() update/delete permissions.
For Web hosts, initialization therefore stays small:
import { initQMuseCloudClient } from '@qmuse/cloud-client/web';
export const cloudClient = await initQMuseCloudClient({
config: () => window.__MUSE__.appwrite,
});functionId is the public physical Function ID assigned by the AppBase project.
It is fixed during initialization and is not supplied by business requests.
New applications should select one platform entry at build time and should not
depend on @qmuse/appwrite or @qmuse/appwrite-runtime-sdk.
The package installs its Appwrite Web SDK dependency automatically. Applications
do not need to declare appwrite separately to use /web. The /miniapp entry
does not import that SDK; it uses the host's Taro runtime through the optional
@tarojs/taro peer dependency. Keep platform imports in branches that the
bundler can remove at build time so native bundles do not include the Web SDK.
Only /api paths and an allowlist of business headers are accepted. The client
uses synchronous Function execution, reads responseStatusCode, responseBody,
and responseHeaders, and maps non-2xx responses to QmuseCloudHttpError. Its optional requestId preserves the correlation ID from a unified error body. New Hono templates return HTTP 400 for handled errors; use error.code, rather than status alone, for business recovery.
Ordinary requests capture the method, path, query, allowed headers and JSON body
when invoked, before Session preparation can yield. Later form edits do not
change that submitted intent. A permitted transport401 retry uses the same body
and business headers. Non-serializable bodies fail before authentication or
submission with BODY_NOT_SERIALIZABLE.
The client never replays a completed Function response, including a business
401, because replaying a write could duplicate side effects. The host adapter is
responsible for Session coordination and may retry createExecution once only
when the execution API request itself fails with a transport-level 401.
The shared Auth runtime checks identity before that retry and before returning a
successful response. Logout, login, explicit Session restore, or renewal to a
different user or role invalidates an in-flight response with AUTH_STATE_CHANGED;
the same applies when a trusted profile response updates the cached role.
Same-user, same-role Session renewal keeps ordinary requests valid. A changed
identity cannot refresh and replay the old request. This applies to file metadata
and access URLs through the same request path. It does not roll back an operation
that already ran on the server; reconcile writes before resubmitting them.
Private access URL delivery additionally verifies the native Account owner,
including after an authenticated Blob read, so a missed Session notice does not
leave the cached owner as the only check. A mismatch rejects with
AUTH_STATE_CHANGED and requires explicit restore. Public URLs keep their
existing account discovery cost; already delivered URLs are not revoked.
Login, provider/miniapp login, logout, and logout-all close the old identity
boundary as soon as they begin. Until that change finishes, new business work,
Session restore/refresh, and a second authentication change fail with
AUTH_STATE_CHANGED. Successful login opens the new identity; successful logout
confirms anonymous public access. After a failed change, preserve the actual
error and explicitly restore the Session before submitting new business work.
The Web entry also sends credential-free Session-change notices between
same-origin tabs, scoped to the AppBase endpoint and Project. Login and logout
invalidate other tabs' cached identity and pending request boundaries. Receiving
a notice also blocks new business requests with AUTH_STATE_CHANGED until an
explicit Session restore or successful login acknowledges the current identity.
Request preparation and identity guards also read the current scoped notice
marker, so a dropped or delayed storage event does not leave the old cache as
the only boundary. This uses local storage and adds no native auth request.
Already observed queued events cannot invalidate an explicitly restored owner.
Session refresh cannot acknowledge this change. Clear old UI data before
loading the restored user's data; no old request is replayed. Ordinary requests
carry an internal expected-user condition, using nonempty @anonymous for
an explicitly anonymous Session so execution transports cannot drop the condition.
Public file routes check it even without a Session, before creating database
capabilities. An owner mismatch reported by native Account
verification or the backend requires the same explicit recovery.
Storage availability and origin boundaries limit these notices. The backend
must still check the initiating-user condition against the verified principal
to protect changes that the SDK has not observed.
Direct Storage upload is an internal data-plane optimization, not a claim that
the bucket ID is secret on the network or that the protocol can only reach the
Function. Private buckets must be configured so client users can create files
but cannot read/update/delete them directly; reads and deletion are authorized
by the backend. The exact fileSecurity + File Token combination remains a
real AppBase E2E gate before production use.
Editor request diagnostics
The /web initializer can report failures of qmuse-cloud-api to the direct
embedding editor, after an explicit, origin-checked diagnostics handshake.
Only pages with the platform's live-preview script[data-qmuse-runtime="config"]
marker participate. Published/standalone pages and native miniapp clients do not
automatically export events.
No global fetch patch, telemetry endpoint, log polling, or automatic repair is
installed. Requests, responses and existing authentication retries are unchanged.
Failed Function executions remain failures. When a terminal failed receipt has
a valid 400–599 status and a bounded public { error: { code, message?, requestId? } }
envelope, request throws QmuseCloudHttpError with its business code, bounded
public message, executionStatus: 'failed' and validated execution/deployment/request
IDs. It does not copy runtime logs or arbitrary error details. Missing, malformed,
oversized, nonterminal or failed/2xx receipts keep EXECUTION_NOT_COMPLETED.
This does not prove a write rolled back and never causes an automatic replay.
Existing QmuseCloudHttpError.status/code handling continues to work.
Reports contain only method/path (without query), time, status/error code and available execution/deployment/request IDs. Bodies, credentials, error messages and SDK raw responses are excluded. Expected 400/401/403/409/422 rejections and aborts are not reported; server errors, failed executions, network failures and 404/405/408/429 responses are diagnostic candidates. Runtime configuration loading and direct Storage transfers are outside this Function-request observer.
Request IDs prefer a valid X-Request-ID response header. If that header is
missing or unusable, a small JSON error envelope may supply its validated
error.requestId. No error text, details or other payload fields are forwarded.
A request ID is correlation metadata and does not imply a W3C Trace ID or
permission to retrieve backend logs.
QmuseCloudClientOptions.onRequestFailure is optional for custom host adapters;
observer failures cannot change request outcomes. The built-in web preview bridge
uses qmuse.cloud-diagnostics version 1 (ready, connect, failure,
disconnect), matches the direct parent's referrer origin, and reports only after
receiving a session ID from that parent. It holds at most 20 startup events for
30 seconds, never posts diagnostic data to a wildcard origin, and cleans up on
page disposal. A missing referrer disables reporting rather than weakening the
origin check. An embedding parent is a trusted diagnostic recipient, not a new
authorization source for backend log access.
The QMuse editor additionally checks the active iframe, cloud architecture, session generation and event fields, groups bounded in-memory incidents, and queries protected backend logs only when the author clicks “排查问题”. This requires both the updated client in the generated app and the updated editor; existing app bundles do not gain the feature merely by deploying the editor.
Development
npm install
npm run ci
npm pack --dry-runPublishing
Set an unpublished semantic version in package.json, authenticate with the
public npm registry, and run:
npm login --registry https://registry.npmjs.org/
npm run publish:publicThe script defaults to the dev dist-tag and also supports latest. Before
publishing it checks the version, npm authentication, duplicate versions, the
full CI command, and package contents, then requires explicit confirmation. It
temporarily normalizes the public package name and registry and restores
package.json when publishing finishes or fails.
Public file uploads
For Hono services configured for anonymous public uploads, files.upload({ resource: 'public-file', file }) can run without an application login. The SDK forwards the upload-specific completion credential internally. A missing credential is a protocol error; it does not trigger login or a guest Session. The file recovery API exposes the original failure through QmuseCloudUploadError.cause and retains its upload reference without cancelling. That reference contains a secret and must be stored privately. A lost initial anonymous intent response cannot be recovered from an idempotency key alone. Private files and avatars continue to require application identity. Login, registration, restore and refresh semantics are unchanged. Public direct uploads may be readable before completion; anonymous delete/cancel is not supported.
Unified HTTP 400 responses retain diagnostic reporting for reserved system codes:
INTERNAL_ERROR, HTTP_ERROR, AUTH_PROVIDER_ERROR, AUTH_PROVIDER_NOT_CONFIGURED,
FUNCTION_CAPABILITY_UNAVAILABLE, FILE_STATE_UNAVAILABLE, AVATAR_URL_UNAVAILABLE,
and TOO_MANY_REQUESTS. Other business rejections remain in the application UI.
Incomplete executions and transport failures retain their existing error semantics;
HTTP 400 alone never triggers session refresh or a retry.
