@tianacloud/serverless 0.1.0 → 0.3.0
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 +182 -0
- package/dist/codec-public.d.ts +4 -0
- package/dist/codec-public.d.ts.map +1 -0
- package/dist/codec-public.js +3 -0
- package/dist/codec-public.js.map +1 -0
- package/dist/functions.d.ts +30 -0
- package/dist/functions.d.ts.map +1 -0
- package/dist/functions.js +170 -0
- package/dist/functions.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/jweixin.js +14 -0
- package/dist/location.d.ts +35 -0
- package/dist/location.d.ts.map +1 -0
- package/dist/location.js +371 -0
- package/dist/location.js.map +1 -0
- package/dist/vault.d.ts +41 -0
- package/dist/vault.d.ts.map +1 -0
- package/dist/vault.js +80 -0
- package/dist/vault.js.map +1 -0
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -91,6 +91,48 @@ Each call owns an independent App connection. Send `BEGIN; ...; COMMIT;` in
|
|
|
91
91
|
one request. Separate calls do not share a connection transaction or TEMP
|
|
92
92
|
state; SQL errors and partial success keep the App's existing semantics.
|
|
93
93
|
|
|
94
|
+
## Buffered frame codec
|
|
95
|
+
|
|
96
|
+
Protocol tools and test fixtures can use the public `@tianacloud/serverless/codec`
|
|
97
|
+
entry point instead of importing internal `dist` files:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import {
|
|
101
|
+
decodeRequestFrameBytes,
|
|
102
|
+
encodeResponseFrameBytes,
|
|
103
|
+
} from "@tianacloud/serverless/codec";
|
|
104
|
+
|
|
105
|
+
const request = decodeRequestFrameBytes(requestBytes);
|
|
106
|
+
const body = new TextEncoder().encode('{"entries":[]}');
|
|
107
|
+
const responseBytes = encodeResponseFrameBytes({
|
|
108
|
+
metadata_version: 1,
|
|
109
|
+
request_id: request.metadata.request_id,
|
|
110
|
+
status: 200,
|
|
111
|
+
status_text: "OK",
|
|
112
|
+
headers: [{ name: "content-type", value: "application/json" }],
|
|
113
|
+
body_length: body.byteLength,
|
|
114
|
+
}, body);
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
This entry point exports `encodeRequestFrameBytes`, `decodeRequestFrameBytes`,
|
|
118
|
+
`encodeResponseFrameBytes`, and `decodeResponseFrameBytes`, plus the
|
|
119
|
+
`DecodedRequestFrame`, `DecodedResponseFrame`, `FetchHeader`, `FetchMethod`,
|
|
120
|
+
`FetchRequestMetadata`, and `FetchResponseMetadata` types. The response decoder
|
|
121
|
+
accepts an optional `{ requestId, method }` argument to check response correlation
|
|
122
|
+
and HEAD semantics. Invalid frames throw `TianaFetchProtocolError`, available
|
|
123
|
+
from the main package entry point.
|
|
124
|
+
|
|
125
|
+
These functions buffer complete Fetch v1 frames and apply the existing metadata
|
|
126
|
+
and body validation. They do not send requests or perform authentication. Keep
|
|
127
|
+
credentials in the outer transport authorization header, outside the frames.
|
|
128
|
+
Streaming helpers and internal `dist/*` paths are not public API. Ordinary
|
|
129
|
+
application callers should continue using `createTianaFetch`.
|
|
130
|
+
|
|
131
|
+
A mock server using the same codec verifies client integration; it does not
|
|
132
|
+
independently prove Gateway interoperability. The conformance tests also compare
|
|
133
|
+
local codec output with the checked-in golden protocol bytes; the installed-package
|
|
134
|
+
test separately checks the public entry point against golden response bytes.
|
|
135
|
+
|
|
94
136
|
## Request diagnostics
|
|
95
137
|
|
|
96
138
|
The adapter generates a request ID before network I/O and sends the same ID
|
|
@@ -343,3 +385,143 @@ already-issued OSS form or immediately release its reservation. A lost complete
|
|
|
343
385
|
response raises `FILE_COMPLETE_UNCERTAIN` with `uploadId`; query the operation
|
|
344
386
|
before starting another upload. MGR's expiry check settles uploads even if the
|
|
345
387
|
browser closes. Browser `onProgress` uses XHR; Node reports transfer completion.
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
## One-shot device location
|
|
391
|
+
|
|
392
|
+
Hosted Tiana apps use the platform-injected capability:
|
|
393
|
+
|
|
394
|
+
```ts
|
|
395
|
+
const position = await window.tiana.location.getCurrentPosition({
|
|
396
|
+
timeoutMs: 20_000,
|
|
397
|
+
signal: abortController.signal,
|
|
398
|
+
});
|
|
399
|
+
// latitude, longitude, accuracy (meters), timestamp (Unix milliseconds),
|
|
400
|
+
// coordinateSystem: "WGS-84"
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
The platform uses `createTianaLocation({signingUrl, sdkUrl, entryUrl})` from this
|
|
404
|
+
package. These are trusted same-origin platform URLs; application code does not
|
|
405
|
+
supply an AppID. The signing service selects its configured WeChat service-account
|
|
406
|
+
identity. The public AppID reaches `wx.config`; secrets, access tokens and tickets
|
|
407
|
+
remain server-side. The original document URL is captured before SPA navigation,
|
|
408
|
+
with only its fragment removed for signing.
|
|
409
|
+
|
|
410
|
+
Mobile WeChat and mini-program **WebViews** use the pinned official JS-SDK;
|
|
411
|
+
ordinary PC/mobile browsers and desktop WeChat use browser Geolocation. Results
|
|
412
|
+
always use WGS-84. This is a frontend device capability: Node/Bun/Deno imports
|
|
413
|
+
remain safe, but a host without a browser returns `UNSUPPORTED` when called.
|
|
414
|
+
Native mini-program application code is outside this WebView API.
|
|
415
|
+
|
|
416
|
+
Import/construction performs no location or signing work. Platform Bootstrap can
|
|
417
|
+
embed the standalone generated implementation without an extra module request.
|
|
418
|
+
The official script and signing are lazy. Permission denial does not trigger a
|
|
419
|
+
second provider or an IP-location service. Accuracy is provided by the device;
|
|
420
|
+
WeChat timestamps describe receipt time rather than an exposed sensor sample time.
|
|
421
|
+
The SDK keeps no position cache/history and sends no coordinates in HTTP, URLs,
|
|
422
|
+
Storage or diagnostics. Browser freshness uses maximumAge=0.
|
|
423
|
+
|
|
424
|
+
Requests have a total 20-second default deadline (integer timeoutMs 1..120000),
|
|
425
|
+
AbortSignal support and a 32-waiter limit per factory. Configuration is shared
|
|
426
|
+
with its own 10-second bound; cancelling one caller does not cancel another.
|
|
427
|
+
Destroy with `dispose()` on page teardown. Late callbacks cannot settle a finished
|
|
428
|
+
call. After failed configuration the official script is reloaded to clear its
|
|
429
|
+
private ready state. The official source is wrapped in a private factory: existing wx/jWeixin globals
|
|
430
|
+
and mini-program navigation remain untouched, including failed loads. Its document
|
|
431
|
+
listeners are removed on failure/disposal. Hosted apps should use this capability
|
|
432
|
+
consistently; coordination of competing business-managed wx.config calls is outside
|
|
433
|
+
the contract.
|
|
434
|
+
|
|
435
|
+
`TianaLocationError.code` is one of `PERMISSION_DENIED`, `UNAVAILABLE`, `TIMEOUT`,
|
|
436
|
+
`ABORTED`, `UNSUPPORTED`, `CONFIGURATION`, `INVALID_RESULT`, `BUSY`, `DISPOSED`.
|
|
437
|
+
Diagnostics contain fixed stage/field codes, never native error text or values.
|
|
438
|
+
Wechat numeric strings are normalized as strict decimals; empty/null/boolean,
|
|
439
|
+
objects, hex, nonfinite values and invalid ranges remain rejected.
|
|
440
|
+
|
|
441
|
+
For local integration only, build this checkout, then explicitly run
|
|
442
|
+
`scripts/sync-location-runtime.mjs PATH_TO_WEB_BOOTSTRAP PATH_TO_CLI_BOOTSTRAP`.
|
|
443
|
+
It embeds a generated scoped region and copies standalone location.js/jweixin.js
|
|
444
|
+
with candidate provenance. Ordinary build/test/pack never reads another checkout.
|
|
445
|
+
Platform release requires immutable SDK release provenance; a local candidate is
|
|
446
|
+
not a published SDK or deployed capability. Existing file/auth resources retain
|
|
447
|
+
their independent pinned provenance. Local CLI preview supports browser location;
|
|
448
|
+
WeChat preview without a trusted signing configuration fails `CONFIGURATION`.
|
|
449
|
+
## Function calls with a browser identity
|
|
450
|
+
|
|
451
|
+
Hosted applications use the current Site login without configuring a persistent
|
|
452
|
+
Function token:
|
|
453
|
+
|
|
454
|
+
```js
|
|
455
|
+
const response = await tiana.functions.fetch('fn-orders', '/orders', {
|
|
456
|
+
method: 'POST',
|
|
457
|
+
headers: { 'Content-Type': 'application/json' },
|
|
458
|
+
body: JSON.stringify({ message: 'hello' }),
|
|
459
|
+
signal: abortController.signal,
|
|
460
|
+
});
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
The Web owner must first select the Function in the Web's allowed list. The
|
|
464
|
+
Bootstrap obtains a short-lived credential through its same-origin Site API,
|
|
465
|
+
then calls the granted Gateway origin directly. Site cookies stay on the Site;
|
|
466
|
+
Function requests use the granted token and omit cookies. Function business
|
|
467
|
+
responses retain their HTTP status and body.
|
|
468
|
+
|
|
469
|
+
Use `websocket(instanceId, path, { protocols?, signal? })` for a native
|
|
470
|
+
WebSocket, returned after its opening handshake:
|
|
471
|
+
|
|
472
|
+
```js
|
|
473
|
+
const socket = await tiana.functions.websocket('fn-orders', '/events?topic=orders', {
|
|
474
|
+
protocols: ['orders'],
|
|
475
|
+
signal: abortController.signal,
|
|
476
|
+
});
|
|
477
|
+
socket.addEventListener('message', event => console.log(event.data));
|
|
478
|
+
socket.send('subscribe');
|
|
479
|
+
// Close the native socket when finished.
|
|
480
|
+
socket.close();
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
The SDK converts the granted HTTPS origin to WSS and supplies its short-lived
|
|
484
|
+
credential as `access_token`, preserving the business path and query. Protocols
|
|
485
|
+
go directly to the native WebSocket constructor. The signal cancels credential
|
|
486
|
+
waiting and the handshake; after open, use `socket.close()` or client `dispose()`.
|
|
487
|
+
Disposal closes all owned connecting and open sockets. Failed handshakes keep
|
|
488
|
+
unexpired grants cached for the next explicit call. There is no reconnect,
|
|
489
|
+
message queue, or automatic business retry. Avoid logging the socket URL, which
|
|
490
|
+
contains its credential.
|
|
491
|
+
|
|
492
|
+
The exported `createTianaFunctions({ connection, fetch? })` is the same client
|
|
493
|
+
used by the Bootstrap. `connection(instanceId, { signal })` belongs to the
|
|
494
|
+
embedding application's authenticated context and returns `instance_id`,
|
|
495
|
+
`origin`, `token`, and absolute Unix-second `expires_at`. Console integrations
|
|
496
|
+
can supply their existing same-origin credential issuer. It is not an account
|
|
497
|
+
refresh provider; no long-lived token discovery or persistence is performed.
|
|
498
|
+
|
|
499
|
+
One client caches grants per Function in memory and shares concurrent grant
|
|
500
|
+
requests. Canceling one caller leaves other waiters running. Grant acquisition
|
|
501
|
+
has a bounded management wait; the caller's AbortSignal controls the business
|
|
502
|
+
request. A 401/403 discards that target's cached grant and returns the response,
|
|
503
|
+
without replaying the business request. Network errors also do not trigger
|
|
504
|
+
replay. Cross-origin target overrides are rejected and HTTP redirects are not
|
|
505
|
+
followed with the credential.
|
|
506
|
+
|
|
507
|
+
Call `dispose()` when logging out or replacing the user/tenant context, then
|
|
508
|
+
create a new client for the new context. Disposal discards late grants and
|
|
509
|
+
cancels outstanding requests. Hosted Bootstrap also discards grants on page
|
|
510
|
+
exit and on detected Site session loss, and creates a fresh client after a
|
|
511
|
+
persisted-page restoration. These SDK tests and browser fixtures do not replace
|
|
512
|
+
acceptance against a deployed Function platform.
|
|
513
|
+
|
|
514
|
+
### Vault
|
|
515
|
+
|
|
516
|
+
`createTianaVault({instanceId, origin, fetch})` uses an authorized `tiana-http`
|
|
517
|
+
transport and exposes `Get`, `Set`, `Remove`, and `List`. Values are UTF-8 strings,
|
|
518
|
+
including empty strings. Version metadata is a decimal string; Set retains the
|
|
519
|
+
version for unchanged values and increments it for changed values. Only the
|
|
520
|
+
current value is stored. List returns key/version metadata and a cursor.
|
|
521
|
+
|
|
522
|
+
Pass `await createVaultSigner(passphrase)` to Get. The displayed Base64 safety
|
|
523
|
+
passphrase becomes a non-exportable Web Crypto key, and each Get is signed for
|
|
524
|
+
its instance, key and current Unix second. The App accepts a 15-second absolute
|
|
525
|
+
clock difference. Acquire the transport credential before Get; expired signatures
|
|
526
|
+
and uncertain mutations are not retried. The caller owns signer/credential
|
|
527
|
+
lifetime and must discard them when its account context ends.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Buffered Fetch v1 frame codecs for protocol tooling and test fixtures. */
|
|
2
|
+
export { decodeRequestFrameBytes, decodeResponseFrameBytes, encodeRequestFrameBytes, encodeResponseFrameBytes, type DecodedRequestFrame, type DecodedResponseFrame, } from "./codec.js";
|
|
3
|
+
export type { FetchHeader, FetchMethod, FetchRequestMetadata, FetchResponseMetadata, } from "./protocol.js";
|
|
4
|
+
//# sourceMappingURL=codec-public.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec-public.d.ts","sourceRoot":"","sources":["../src/codec-public.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,GAC1B,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,WAAW,EACX,WAAW,EACX,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,eAAe,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec-public.js","sourceRoot":"","sources":["../src/codec-public.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,GAGzB,MAAM,YAAY,CAAC","sourcesContent":["/** Buffered Fetch v1 frame codecs for protocol tooling and test fixtures. */\nexport {\n decodeRequestFrameBytes,\n decodeResponseFrameBytes,\n encodeRequestFrameBytes,\n encodeResponseFrameBytes,\n type DecodedRequestFrame,\n type DecodedResponseFrame,\n} from \"./codec.js\";\nexport type {\n FetchHeader,\n FetchMethod,\n FetchRequestMetadata,\n FetchResponseMetadata,\n} from \"./protocol.js\";\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface TianaFunctionConnection {
|
|
2
|
+
readonly instance_id: string;
|
|
3
|
+
readonly origin: string;
|
|
4
|
+
readonly token: string;
|
|
5
|
+
/** Absolute Unix seconds, supplied by the credential issuer. */
|
|
6
|
+
readonly expires_at: number;
|
|
7
|
+
}
|
|
8
|
+
export interface TianaFunctionsOptions {
|
|
9
|
+
/** Bound to one authenticated Site or Console context. */
|
|
10
|
+
readonly connection: (instanceId: string, options: {
|
|
11
|
+
readonly signal: AbortSignal;
|
|
12
|
+
}) => Promise<TianaFunctionConnection>;
|
|
13
|
+
/** Direct Gateway transport, independent of the connection issuer. */
|
|
14
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
15
|
+
}
|
|
16
|
+
export interface TianaFunctionWebSocketOptions {
|
|
17
|
+
/** Business subprotocols passed directly to the native constructor. */
|
|
18
|
+
readonly protocols?: string | string[];
|
|
19
|
+
/** Cancels credential acquisition and handshake only, until open. */
|
|
20
|
+
readonly signal?: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
export interface TianaFunctions {
|
|
23
|
+
websocket(instanceId: string, path: string, options?: TianaFunctionWebSocketOptions): Promise<WebSocket>;
|
|
24
|
+
fetch(instanceId: string, path: string, init?: RequestInit): Promise<Response>;
|
|
25
|
+
/** Discard credentials and cancel outstanding work when the context ends. */
|
|
26
|
+
dispose(): void;
|
|
27
|
+
}
|
|
28
|
+
/** One client per login context; no persistence or automatic business retries. */
|
|
29
|
+
export declare function createTianaFunctions(options: TianaFunctionsOptions): TianaFunctions;
|
|
30
|
+
//# sourceMappingURL=functions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["../src/functions.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,gEAAgE;IAChE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,qBAAqB;IACpC,0DAA0D;IAC1D,QAAQ,CAAC,UAAU,EAAE,CACnB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;KAAE,KACtC,OAAO,CAAC,uBAAuB,CAAC,CAAC;IACtC,sEAAsE;IACtE,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CAC1C;AAED,MAAM,WAAW,6BAA6B;IAC5C,uEAAuE;IACvE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACvC,qEAAqE;IACrE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,6BAA6B,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IACzG,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC/E,6EAA6E;IAC7E,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,kFAAkF;AAClF,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CA+InF"}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { waitFor } from "./auth.js";
|
|
2
|
+
/** One client per login context; no persistence or automatic business retries. */
|
|
3
|
+
export function createTianaFunctions(options) {
|
|
4
|
+
const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
5
|
+
const lifetime = new AbortController();
|
|
6
|
+
const sockets = new Map();
|
|
7
|
+
const credentials = new Map();
|
|
8
|
+
const pending = new Map();
|
|
9
|
+
function active() {
|
|
10
|
+
lifetime.signal.throwIfAborted();
|
|
11
|
+
}
|
|
12
|
+
function usable(value) {
|
|
13
|
+
return value.expires_at * 1000 > Date.now();
|
|
14
|
+
}
|
|
15
|
+
function validate(instanceId, value) {
|
|
16
|
+
let origin;
|
|
17
|
+
try {
|
|
18
|
+
origin = new URL(value.origin);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new Error("Invalid Function connection");
|
|
22
|
+
}
|
|
23
|
+
if (value.instance_id !== instanceId || origin.protocol !== "https:" ||
|
|
24
|
+
origin.username || origin.password || origin.pathname !== "/" ||
|
|
25
|
+
origin.search || origin.hash || typeof value.token !== "string" ||
|
|
26
|
+
!value.token || /[\s\x00-\x1f\x7f]/u.test(value.token) || !Number.isSafeInteger(value.expires_at) || !usable(value)) {
|
|
27
|
+
throw new Error("Invalid or expired Function connection");
|
|
28
|
+
}
|
|
29
|
+
return Object.freeze({ ...value, origin: origin.origin });
|
|
30
|
+
}
|
|
31
|
+
async function connection(instanceId) {
|
|
32
|
+
active();
|
|
33
|
+
const cached = credentials.get(instanceId);
|
|
34
|
+
if (cached && usable(cached))
|
|
35
|
+
return cached;
|
|
36
|
+
credentials.delete(instanceId);
|
|
37
|
+
let current = pending.get(instanceId);
|
|
38
|
+
if (!current) {
|
|
39
|
+
// The existing browser management wait is bounded independently of callers.
|
|
40
|
+
const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(15000)]);
|
|
41
|
+
current = Promise.resolve().then(async () => {
|
|
42
|
+
signal.throwIfAborted();
|
|
43
|
+
const value = validate(instanceId, await waitFor(options.connection(instanceId, { signal }), signal));
|
|
44
|
+
active();
|
|
45
|
+
credentials.set(instanceId, value);
|
|
46
|
+
return value;
|
|
47
|
+
}).finally(() => { pending.delete(instanceId); });
|
|
48
|
+
pending.set(instanceId, current);
|
|
49
|
+
}
|
|
50
|
+
return current;
|
|
51
|
+
}
|
|
52
|
+
return Object.freeze({
|
|
53
|
+
async fetch(instanceId, path, init = {}) {
|
|
54
|
+
active();
|
|
55
|
+
const signal = init.signal
|
|
56
|
+
? AbortSignal.any([lifetime.signal, init.signal]) : lifetime.signal;
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
const credential = await waitFor(connection(instanceId), signal);
|
|
59
|
+
signal.throwIfAborted();
|
|
60
|
+
if (!usable(credential)) {
|
|
61
|
+
credentials.delete(instanceId);
|
|
62
|
+
throw new Error("Function credential expired before dispatch");
|
|
63
|
+
}
|
|
64
|
+
const url = new URL(path, credential.origin);
|
|
65
|
+
if (url.origin !== credential.origin || url.username || url.password) {
|
|
66
|
+
throw new TypeError("Function request must use its authorized origin");
|
|
67
|
+
}
|
|
68
|
+
const headers = new Headers(init.headers);
|
|
69
|
+
headers.set("Authorization", "Bearer " + credential.token);
|
|
70
|
+
const response = await transport(url, {
|
|
71
|
+
...init, headers, signal, credentials: "omit", redirect: "error",
|
|
72
|
+
});
|
|
73
|
+
if ((response.status === 401 || response.status === 403) && credentials.get(instanceId) === credential) {
|
|
74
|
+
credentials.delete(instanceId);
|
|
75
|
+
}
|
|
76
|
+
return response;
|
|
77
|
+
},
|
|
78
|
+
async websocket(instanceId, path, options = {}) {
|
|
79
|
+
active();
|
|
80
|
+
const signal = options.signal
|
|
81
|
+
? AbortSignal.any([lifetime.signal, options.signal]) : lifetime.signal;
|
|
82
|
+
signal.throwIfAborted();
|
|
83
|
+
const credential = await waitFor(connection(instanceId), signal);
|
|
84
|
+
signal.throwIfAborted();
|
|
85
|
+
if (!usable(credential)) {
|
|
86
|
+
credentials.delete(instanceId);
|
|
87
|
+
throw new Error("Function credential expired before dispatch");
|
|
88
|
+
}
|
|
89
|
+
let url;
|
|
90
|
+
try {
|
|
91
|
+
url = new URL(path, credential.origin);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
throw new TypeError("Invalid Function WebSocket path");
|
|
95
|
+
}
|
|
96
|
+
if (url.origin !== credential.origin || url.username || url.password) {
|
|
97
|
+
throw new TypeError("Function request must use its authorized origin");
|
|
98
|
+
}
|
|
99
|
+
url.protocol = "wss:";
|
|
100
|
+
url.searchParams.set("access_token", credential.token);
|
|
101
|
+
let socket;
|
|
102
|
+
try {
|
|
103
|
+
socket = new WebSocket(url, options.protocols);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new Error("Function WebSocket construction failed");
|
|
107
|
+
}
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
let opened = false;
|
|
110
|
+
const cleanupHandshake = () => {
|
|
111
|
+
socket.removeEventListener("open", onOpen);
|
|
112
|
+
socket.removeEventListener("error", onError);
|
|
113
|
+
signal.removeEventListener("abort", onAbort);
|
|
114
|
+
};
|
|
115
|
+
const release = () => {
|
|
116
|
+
cleanupHandshake();
|
|
117
|
+
socket.removeEventListener("close", onClose);
|
|
118
|
+
sockets.delete(socket);
|
|
119
|
+
};
|
|
120
|
+
const fail = (error) => {
|
|
121
|
+
release();
|
|
122
|
+
// Native close may throw for a connecting socket in some runtimes.
|
|
123
|
+
try {
|
|
124
|
+
socket.close();
|
|
125
|
+
}
|
|
126
|
+
catch { /* Ownership is already released. */ }
|
|
127
|
+
reject(error);
|
|
128
|
+
};
|
|
129
|
+
const onOpen = () => {
|
|
130
|
+
opened = true;
|
|
131
|
+
cleanupHandshake();
|
|
132
|
+
resolve(socket);
|
|
133
|
+
};
|
|
134
|
+
const onError = () => fail(new Error("Function WebSocket handshake failed"));
|
|
135
|
+
const onClose = () => {
|
|
136
|
+
if (opened)
|
|
137
|
+
release();
|
|
138
|
+
else
|
|
139
|
+
fail(new Error("Function WebSocket closed before open"));
|
|
140
|
+
};
|
|
141
|
+
const onAbort = () => fail(new DOMException("Function WebSocket handshake cancelled", "AbortError"));
|
|
142
|
+
sockets.set(socket, () => {
|
|
143
|
+
if (opened) {
|
|
144
|
+
release();
|
|
145
|
+
try {
|
|
146
|
+
socket.close();
|
|
147
|
+
}
|
|
148
|
+
catch { /* Ownership is already released. */ }
|
|
149
|
+
}
|
|
150
|
+
else
|
|
151
|
+
onAbort();
|
|
152
|
+
});
|
|
153
|
+
socket.addEventListener("open", onOpen);
|
|
154
|
+
socket.addEventListener("error", onError);
|
|
155
|
+
socket.addEventListener("close", onClose);
|
|
156
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
157
|
+
if (signal.aborted)
|
|
158
|
+
onAbort();
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
dispose() {
|
|
162
|
+
lifetime.abort(new DOMException("Function context ended", "AbortError"));
|
|
163
|
+
for (const close of sockets.values())
|
|
164
|
+
close();
|
|
165
|
+
credentials.clear();
|
|
166
|
+
pending.clear();
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
//# sourceMappingURL=functions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions.js","sourceRoot":"","sources":["../src/functions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAkCpC,kFAAkF;AAClF,MAAM,UAAU,oBAAoB,CAAC,OAA8B;IACjE,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACrE,MAAM,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAC;IACvC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAyB,CAAC;IACjD,MAAM,WAAW,GAAG,IAAI,GAAG,EAAmC,CAAC;IAC/D,MAAM,OAAO,GAAG,IAAI,GAAG,EAA4C,CAAC;IAEpE,SAAS,MAAM;QACb,QAAQ,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;IACnC,CAAC;IACD,SAAS,MAAM,CAAC,KAA8B;QAC5C,OAAO,KAAK,CAAC,UAAU,GAAG,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAC9C,CAAC;IACD,SAAS,QAAQ,CAAC,UAAkB,EAAE,KAA8B;QAClE,IAAI,MAAW,CAAC;QAChB,IAAI,CAAC;YAAC,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAAC,CAAC;QACvC,MAAM,CAAC;YAAC,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAAC,CAAC;QACzD,IAAI,KAAK,CAAC,WA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AAC;;wBAAM,OAAO,EAAE,CAAC;gBACnB,CAAC,CAAC,CAAC;gBACH,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;gBACxC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;gBAC1C,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;gBAC1C,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC1D,IAAI,MAAM,CAAC,OAAO;oBAAE,OAAO,EAAE,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAO;YACL,QAAQ,CAAC,KAAK,CAAC,IAAI,YAAY,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC,CAAC;YACzE,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,MAAM,EAAE;gBAAE,KAAK,EAAE,CAAC;YAC9C,WAAW,CAAC,KAAK,EAAE,CAAC;YACpB,OAAO,CAAC,KAAK,EAAE,CAAC;QAClB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { waitFor } from \"./auth.js\";\n\nexport interface TianaFunctionConnection {\n readonly instance_id: string;\n readonly origin: string;\n readonly token: string;\n /** Absolute Unix seconds, supplied by the credential issuer. */\n readonly expires_at: number;\n}\n\nexport interface TianaFunctionsOptions {\n /** Bound to one authenticated Site or Console context. */\n readonly connection: (\n instanceId: string,\n options: { readonly signal: AbortSignal },\n ) => Promise<TianaFunctionConnection>;\n /** Direct Gateway transport, independent of the connection issuer. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\nexport interface TianaFunctionWebSocketOptions {\n /** Business subprotocols passed directly to the native constructor. */\n readonly protocols?: string | string[];\n /** Cancels credential acquisition and handshake only, until open. */\n readonly signal?: AbortSignal;\n}\n\nexport interface TianaFunctions {\n websocket(instanceId: string, path: string, options?: TianaFunctionWebSocketOptions): Promise<WebSocket>;\n fetch(instanceId: string, path: string, init?: RequestInit): Promise<Response>;\n /** Discard credentials and cancel outstanding work when the context ends. */\n dispose(): void;\n}\n\n/** One client per login context; no persistence or automatic business retries. */\nexport function createTianaFunctions(options: TianaFunctionsOptions): TianaFunctions {\n const transport = options.fetch ?? globalThis.fetch.bind(globalThis);\n const lifetime = new AbortController();\n const sockets = new Map<WebSocket, () => void>();\n const credentials = new Map<string, TianaFunctionConnection>();\n const pending = new Map<string, Promise<TianaFunctionConnection>>();\n\n function active(): void {\n lifetime.signal.throwIfAborted();\n }\n function usable(value: TianaFunctionConnection): boolean {\n return value.expires_at * 1000 > Date.now();\n }\n function validate(instanceId: string, value: TianaFunctionConnection): TianaFunctionConnection {\n let origin: URL;\n try { origin = new URL(value.origin); }\n catch { throw new Error(\"Invalid Function connection\"); }\n if (value.instance_id !== instanceId || origin.protocol !== \"https:\" ||\n origin.username || origin.password || origin.pathname !== \"/\" ||\n origin.search || origin.hash || typeof value.token !== \"string\" ||\n !value.token || /[\\s\\x00-\\x1f\\x7f]/u.test(value.token) || !Number.isSafeInteger(value.expires_at) || !usable(value)) {\n throw new Error(\"Invalid or expired Function connection\");\n }\n return Object.freeze({ ...value, origin: origin.origin });\n }\n async function connection(instanceId: string): Promise<TianaFunctionConnection> {\n active();\n const cached = credentials.get(instanceId);\n if (cached && usable(cached)) return cached;\n credentials.delete(instanceId);\n let current = pending.get(instanceId);\n if (!current) {\n // The existing browser management wait is bounded independently of callers.\n const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(15000)]);\n current = Promise.resolve().then(async () => {\n signal.throwIfAborted();\n const value = validate(instanceId, await waitFor(options.connection(instanceId, { signal }), signal));\n active();\n credentials.set(instanceId, value);\n return value;\n }).finally(() => { pending.delete(instanceId); });\n pending.set(instanceId, current);\n }\n return current;\n }\n\n return Object.freeze({\n async fetch(instanceId: string, path: string, init: RequestInit = {}): Promise<Response> {\n active();\n const signal = init.signal\n ? AbortSignal.any([lifetime.signal, init.signal]) : lifetime.signal;\n signal.throwIfAborted();\n const credential = await waitFor(connection(instanceId), signal);\n signal.throwIfAborted();\n if (!usable(credential)) {\n credentials.delete(instanceId);\n throw new Error(\"Function credential expired before dispatch\");\n }\n const url = new URL(path, credential.origin);\n if (url.origin !== credential.origin || url.username || url.password) {\n throw new TypeError(\"Function request must use its authorized origin\");\n }\n const headers = new Headers(init.headers);\n headers.set(\"Authorization\", \"Bearer \" + credential.token);\n const response = await transport(url, {\n ...init, headers, signal, credentials: \"omit\", redirect: \"error\",\n });\n if ((response.status === 401 || response.status === 403) && credentials.get(instanceId) === credential) {\n credentials.delete(instanceId);\n }\n return response;\n },\n async websocket(instanceId: string, path: string, options: TianaFunctionWebSocketOptions = {}): Promise<WebSocket> {\n active();\n const signal = options.signal\n ? AbortSignal.any([lifetime.signal, options.signal]) : lifetime.signal;\n signal.throwIfAborted();\n const credential = await waitFor(connection(instanceId), signal);\n signal.throwIfAborted();\n if (!usable(credential)) {\n credentials.delete(instanceId);\n throw new Error(\"Function credential expired before dispatch\");\n }\n let url: URL;\n try { url = new URL(path, credential.origin); }\n catch { throw new TypeError(\"Invalid Function WebSocket path\"); }\n if (url.origin !== credential.origin || url.username || url.password) {\n throw new TypeError(\"Function request must use its authorized origin\");\n }\n url.protocol = \"wss:\";\n url.searchParams.set(\"access_token\", credential.token);\n let socket: WebSocket;\n try { socket = new WebSocket(url, options.protocols); }\n catch { throw new Error(\"Function WebSocket construction failed\"); }\n return new Promise<WebSocket>((resolve, reject) => {\n let opened = false;\n const cleanupHandshake = (): void => {\n socket.removeEventListener(\"open\", onOpen);\n socket.removeEventListener(\"error\", onError);\n signal.removeEventListener(\"abort\", onAbort);\n };\n const release = (): void => {\n cleanupHandshake();\n socket.removeEventListener(\"close\", onClose);\n sockets.delete(socket);\n };\n const fail = (error: unknown): void => {\n release();\n // Native close may throw for a connecting socket in some runtimes.\n try { socket.close(); } catch { /* Ownership is already released. */ }\n reject(error);\n };\n const onOpen = (): void => {\n opened = true;\n cleanupHandshake();\n resolve(socket);\n };\n const onError = (): void => fail(new Error(\"Function WebSocket handshake failed\"));\n const onClose = (): void => {\n if (opened) release();\n else fail(new Error(\"Function WebSocket closed before open\"));\n };\n const onAbort = (): void => fail(new DOMException(\"Function WebSocket handshake cancelled\", \"AbortError\"));\n sockets.set(socket, () => {\n if (opened) {\n release();\n try { socket.close(); } catch { /* Ownership is already released. */ }\n } else onAbort();\n });\n socket.addEventListener(\"open\", onOpen);\n socket.addEventListener(\"error\", onError);\n socket.addEventListener(\"close\", onClose);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n if (signal.aborted) onAbort();\n });\n },\n dispose(): void {\n lifetime.abort(new DOMException(\"Function context ended\", \"AbortError\"));\n for (const close of sockets.values()) close();\n credentials.clear();\n pending.clear();\n },\n });\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -38,4 +38,10 @@ export type TianaOuterErrorCode = FetchErrorCode;
|
|
|
38
38
|
export type TianaOuterErrorResponse = FetchErrorResponse;
|
|
39
39
|
export { createTianaFiles, TianaFileError } from "./files.js";
|
|
40
40
|
export type { TianaFiles, TianaFilesOptions, TianaFile, TianaFilePage, TianaFileCapabilities, TianaFileGrant, TianaFileUpload, TianaFileRequest, TianaFileRequestOptions, TianaFilePutOptions, } from "./files.js";
|
|
41
|
+
export { createTianaLocation, TianaLocationError } from './location.js';
|
|
42
|
+
export type { TianaLocation, TianaLocationOptions, TianaLocationRequestOptions, TianaLocationErrorCode, TianaPosition } from './location.js';
|
|
43
|
+
export { createTianaFunctions } from "./functions.js";
|
|
44
|
+
export type { TianaFunctions, TianaFunctionsOptions, TianaFunctionConnection, TianaFunctionWebSocketOptions } from "./functions.js";
|
|
45
|
+
export { createTianaVault, createVaultSigner, VaultError } from "./vault.js";
|
|
46
|
+
export type { TianaVault, VaultSigner, VaultEntry, VaultSecret, VaultSetResult, VaultPage } from "./vault.js";
|
|
41
47
|
//# sourceMappingURL=index.d.ts.map
|
package/dist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,kBAAkB,CAAC;AAEzD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC9D,YAAY,EACV,UAAU,EAAE,iBAAiB,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,EAC9E,cAAc,EAAE,eAAe,EAAE,gBAAgB,EAAE,uBAAuB,EAC1E,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACxE,YAAY,EAAE,aAAa,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC7I,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,YAAY,EAAE,cAAc,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,6BAA6B,EAAE,MAAM,gBAAgB,CAAC;AAEpI,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7E,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -367,4 +367,7 @@ export function createTianaFetch(options) {
|
|
|
367
367
|
};
|
|
368
368
|
}
|
|
369
369
|
export { createTianaFiles, TianaFileError } from "./files.js";
|
|
370
|
+
export { createTianaLocation, TianaLocationError } from './location.js';
|
|
371
|
+
export { createTianaFunctions } from "./functions.js";
|
|
372
|
+
export { createTianaVault, createVaultSigner, VaultError } from "./vault.js";
|
|
370
373
|
//# sourceMappingURL=index.js.map
|