@tianacloud/serverless 0.1.0-beta.4 → 0.2.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -5,7 +5,7 @@ Tiana Fetch-over-HTTPS v1. It converts one standard same-origin `fetch()`
5
5
  request into a TFQ1 request to the Tiana Gateway and exposes the TFS1 inner
6
6
  response as a standard `Response`.
7
7
 
8
- Install the prerelease with `npm install @tianacloud/serverless@next`. Its historical Fetch v1 compatibility baseline is
8
+ Install the stable release with `npm install @tianacloud/serverless`. Its historical Fetch v1 compatibility baseline is
9
9
  Contracts release `v0.17.2-rc.1` at commit
10
10
  `d252fd7bf689657e50b6caf36298f8c57860df6b` (annotated tag object
11
11
  `fb4fdf07f6e5b86eb00562f07dccf7bd120cd0f2`).
@@ -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
@@ -136,7 +178,7 @@ Configure npm's trusted publisher once for package `@tianacloud/serverless`,
136
178
  repository `tianacloud/serverless-js`, workflow `release.yml`, with direct
137
179
  publishing allowed. GitHub-hosted runners use OIDC; publication requires no stored
138
180
  npm token or per-release browser verification. npm may require account 2FA when
139
- initially creating this relationship. Prereleases use the package's `next` tag.
181
+ initially creating this relationship. Stable releases use the package's `latest` tag.
140
182
 
141
183
  ## Development
142
184
 
@@ -343,3 +385,64 @@ 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`.
@@ -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,3 @@
1
+ /** Buffered Fetch v1 frame codecs for protocol tooling and test fixtures. */
2
+ export { decodeRequestFrameBytes, decodeResponseFrameBytes, encodeRequestFrameBytes, encodeResponseFrameBytes, } from "./codec.js";
3
+ //# sourceMappingURL=codec-public.js.map
@@ -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"]}
package/dist/index.d.ts CHANGED
@@ -38,4 +38,6 @@ 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';
41
43
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACtF,OAAO,EAAE,WAAW,EAAE,KAAK,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAA2B,KAAK,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC5E,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACnE,YAAY,EACV,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB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HANGED
@@ -367,4 +367,5 @@ export function createTianaFetch(options) {
367
367
  };
368
368
  }
369
369
  export { createTianaFiles, TianaFileError } from "./files.js";
370
+ export { createTianaLocation, TianaLocationError } from './location.js';
370
371
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAwB,MAAM,kBAAkB,CAAC;AACtF,OAAO,EAAE,WAAW,EAAwB,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,cAAc,EAA0B,MAAM,WAAW,CAAC;AAC5E,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAOnE,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EACL,mBAAmB,EACnB,sBAAsB,EACtB,0BAA0B,EAC1B,gBAAgB,EAChB,UAAU,EACV,4BAA4B,EAC5B,uBAAuB,GAOxB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAsCtD,MAAM,uBAAuB,GAC3B,+CAA+C,CAAC;AAClD,MAAM,cAAc,GAAG,IAAI,GAAG,CAAc;IAC1C,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,OAAO;IACP,QAAQ;IACR,SAAS;CACV,CAAC,CAAC;AAEH,SAAS,eAAe,CAAC,KAAmB;IAC1C,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,KAAK,YAAY,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IACpE,CAAC;IAAC,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,CAAC;AAOD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC","sourcesContent":["import { diagnostics, createRequestId, type TianaDiagnostic } from \"./diagnostics.js\";\nexport { diagnosisOf, type TianaDiagnostic } from \"./diagnostics.js\";\nimport { waitFor, TianaAuthError, type TianaAuthProvider } from \"./auth.js\";\nexport { createTianaSessionAuth, TianaAuthError } from \"./auth.js\";\nexport type {\n TianaAuthProvider,\n TianaSessionAuthOptions,\n TianaSessionCredentials,\n TianaAuthErrorCode,\n} from \"./auth.js\";\nimport {\n createRequestFrameStream,\n encodeRequestFrameBytes,\n decodeResponseStream,\n} from \"./codec.js\";\nimport { protocolError } from \"./errors.js\";\nimport {\n decodeErrorResponse,\n FETCH_ERROR_MEDIA_TYPE,\n FETCH_MAX_ERROR_BODY_BYTES,\n FETCH_MEDIA_TYPE,\n FETCH_PATH,\n FETCH_MAX_REQUEST_BODY_BYTES,\n isRegisteredOuterStatus,\n type FetchError,\n type FetchErrorCode,\n type FetchErrorResponse,\n type FetchHeader,\n type FetchMethod,\n type FetchRequestMetadata,\n} from \"./protocol.js\";\n\nexport { TianaFetchProtocolError } from \"./errors.js\";\nexport type {\n FetchError,\n FetchErrorCode,\n FetchErrorResponse,\n FetchHeader,\n FetchQuotaReason,\n} from \"./protocol.js\";\n\nexport type TianaFetch = (\n input: RequestInfo | URL,\n init?: RequestInit,\n) => Promise<Response>;\n\ninterface TianaFetchBaseOptions {\n /** The sole HTTPS database origin accepted by this adapter. */\n readonly origin: string | URL;\n\n /** Select the App HTTP data socket. Omit for the native data socket. */\n readonly protocol?: \"tiana-http\";\n\n /** Buffer the request frame for browser transports without upload streaming. */\n readonly requestBodyMode?: \"stream\" | \"buffered\";\n\n /** Optional platform-compatible transport. It is invoked exactly once. */\n readonly fetch?: typeof globalThis.fetch;\n\n /** Per-request diagnostic events; callback failures do not affect Fetch. */\n readonly onDiagnostic?: (diagnostic: TianaDiagnostic) => void;\n}\n\n/** Exactly one credential source; the provider is shared across requests. */\nexport type TianaFetchOptions = TianaFetchBaseOptions &\n (\n | { readonly tianaToken: string; readonly auth?: never }\n | { readonly auth: TianaAuthProvider; readonly tianaToken?: never }\n );\n\nconst endpointHostnamePattern =\n /^ep-[0-7][0-9a-hjkmnp-tv-z]{25}\\.[a-z0-9.-]+$/;\nconst allowedMethods = new Set<FetchMethod>([\n \"GET\",\n \"HEAD\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"OPTIONS\",\n]);\n\nfunction normalizeOrigin(value: string | URL): string {\n let url: URL;\n try {\n url = value instanceof URL ? new URL(value.href) : new URL(value);\n } catch {\n throw new TypeError(\"Tiana origin must be an absolute HTTPS origin URL\");\n }\n if (\n url.protocol !== \"https:\" ||\n url.username !== \"\" ||\n url.password !== \"\" ||\n url.pathname !== \"/\" ||\n url.search !== \"\" ||\n url.hash !== \"\"\n ) {\n throw new TypeError(\"Tiana origin must be an absolute HTTPS origin URL\");\n }\n const hostname = url.hostname.toLowerCase();\n if (!endpointHostnamePattern.test(hostname)) {\n throw new TypeError(\"Tiana origin must contain a valid v1 Endpoint ID and DNS suffix\");\n }\n return url.origin;\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n\nfunction normalizedHeaders(request: Request): FetchHeader[] {\n return Array.from(request.headers.entries(), ([name, value]) => ({\n name,\n value,\n }));\n}\n\nfunction decodePercentEscapedBytes(value: string): string {\n return value.replace(\n /%([0-9a-f]{2})/gi,\n (_escape, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)),\n );\n}\n\nfunction requestMetadata(\n request: Request,\n tianaToken: string,\n requestId: string,\n): FetchRequestMetadata {\n const url = new URL(request.url);\n if (!allowedMethods.has(request.method as FetchMethod)) {\n throw new TypeError(\"Tiana Fetch does not support this request method\");\n }\n const method = request.method as FetchMethod;\n const pathQuery = `${url.pathname}${url.search}`;\n const headers = normalizedHeaders(request);\n const normalizedToken = tianaToken.toLowerCase();\n if (\n pathQuery.includes(tianaToken) ||\n decodePercentEscapedBytes(pathQuery).includes(tianaToken) ||\n headers.some(\n ({ name, value }) =>\n name.includes(normalizedToken) || value.includes(tianaToken),\n )\n ) {\n throw protocolError(\n \"The outer Tiana Token must not appear in inner Fetch metadata\",\n );\n }\n return {\n metadata_version: 1,\n request_id: requestId,\n method,\n path_query: pathQuery,\n headers,\n body_length:\n method === \"GET\" || method === \"HEAD\" || request.body === null ? 0 : null,\n };\n}\n\nasync function requireOuterHeaders(\n response: Response,\n contentType: string,\n): Promise<void> {\n try {\n if (response.headers.get(\"cache-control\") !== \"no-store\") {\n throw protocolError(\"Fetch outer response is missing Cache-Control: no-store\");\n }\n if (response.headers.get(\"content-type\") !== contentType) {\n throw protocolError(\"Fetch outer response has an invalid Content-Type\");\n }\n const contentEncoding = response.headers.get(\"content-encoding\");\n if (contentEncoding !== null && contentEncoding !== \"identity\") {\n throw protocolError(\"Fetch outer response has an invalid Content-Encoding\");\n }\n if (response.redirected) {\n throw protocolError(\"Fetch outer response must not follow redirects\");\n }\n } catch (error) {\n await response.body?.cancel(error).catch(() => undefined);\n throw error;\n }\n}\n\nasync function readBoundedBody(\n body: ReadableStream<Uint8Array> | null,\n maximum: number,\n): Promise<Uint8Array> {\n if (body === null) {\n throw protocolError(\"Fetch outer response body is missing\");\n }\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n try {\n for (;;) {\n const result = await reader.read();\n if (result.done) {\n break;\n }\n if (result.value.byteLength === 0) {\n continue;\n }\n length += result.value.byteLength;\n if (length > maximum) {\n throw protocolError(\"Fetch outer response body exceeds the SDK bound\");\n }\n chunks.push(result.value);\n }\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n throw error;\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\nasync function readRequestBody(request: Request): Promise<Uint8Array> {\n if (request.signal.aborted) throw abortReason(request.signal);\n let onAbort: () => void = () => undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(abortReason(request.signal));\n request.signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n const body = new Uint8Array(await Promise.race([request.arrayBuffer(), aborted]));\n if (request.signal.aborted) throw abortReason(request.signal);\n if (body.byteLength > FETCH_MAX_REQUEST_BODY_BYTES) throw protocolError(\"Fetch body exceeds the SDK bound\");\n return body;\n } finally {\n request.signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction responseWithUrl(response: Response, url: string): Response {\n try {\n Object.defineProperty(response, \"url\", {\n configurable: true,\n enumerable: false,\n value: url,\n });\n } catch {\n // URL is supplemental metadata. Fetch body/status/header semantics remain\n // correct on runtimes that do not permit defining an own URL property.\n }\n return response;\n}\n\nasync function outerErrorResponse(\n outer: Response,\n requestUrl: string,\n): Promise<Response> {\n if (!isRegisteredOuterStatus(outer.status)) {\n await outer.body?.cancel().catch(() => undefined);\n throw protocolError(\"Fetch outer response status is not registered\");\n }\n await requireOuterHeaders(outer, FETCH_ERROR_MEDIA_TYPE);\n if (outer.status === 405 && outer.headers.get(\"allow\") !== \"POST\") {\n await outer.body?.cancel().catch(() => undefined);\n throw protocolError(\"Fetch 405 response is missing Allow: POST\");\n }\n const body = await readBoundedBody(outer.body, FETCH_MAX_ERROR_BODY_BYTES);\n decodeErrorResponse(body, outer.status);\n return responseWithUrl(\n new Response(new Uint8Array(body), {\n status: outer.status,\n statusText: outer.statusText,\n headers: new Headers(outer.headers),\n }),\n requestUrl,\n );\n}\n\nfunction innerHeaders(headers: readonly FetchHeader[]): Headers {\n const result = new Headers();\n for (const { name, value } of headers) {\n result.append(name, value);\n }\n return result;\n}\n\nasync function innerResponse(\n outer: Response,\n request: Request,\n metadata: FetchRequestMetadata,\n onBodyComplete: () => void,\n onBodyError: (error: unknown) => void,\n onBodyCancel: (reason: unknown) => void,\n): Promise<Response> {\n await requireOuterHeaders(outer, FETCH_MEDIA_TYPE);\n if (outer.body === null) {\n throw protocolError(\"Fetch TFS1 response body is missing\");\n }\n const decoded = await decodeResponseStream(outer.body, {\n requestId: metadata.request_id,\n method: metadata.method,\n onBodyComplete,\n onBodyError,\n onBodyCancel,\n });\n return responseWithUrl(\n new Response(decoded.body, {\n status: decoded.metadata.status,\n statusText: decoded.metadata.status_text,\n headers: innerHeaders(decoded.metadata.headers),\n }),\n request.url,\n );\n}\n\n/**\n * Create a standard Fetch-compatible adapter for one exact Tiana database\n * origin. The returned function performs exactly one outer request and never\n * retries automatically.\n */\nexport function createTianaFetch(options: TianaFetchOptions): TianaFetch {\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"Tiana Fetch options are required\");\n }\n if (options.protocol !== undefined && options.protocol !== \"tiana-http\") {\n throw new TypeError(\"Unsupported Tiana Fetch protocol\");\n }\n const protocol = options.protocol;\n const requestBodyMode = options.requestBodyMode ?? \"stream\";\n if (requestBodyMode !== \"stream\" && requestBodyMode !== \"buffered\") {\n throw new TypeError(\"requestBodyMode must be either stream or buffered\");\n }\n const origin = normalizeOrigin(options.origin);\n const provider = options.auth;\n const staticToken = options.tianaToken;\n if (\n provider !== undefined\n ? staticToken !== undefined ||\n typeof provider?.getAccessToken !== \"function\"\n : typeof staticToken !== \"string\" || staticToken.length === 0\n ) {\n throw new TypeError(\"Exactly one of tianaToken or auth is required\");\n }\n const fetchImplementation =\n options.fetch ?? globalThis.fetch?.bind(globalThis);\n if (typeof fetchImplementation !== \"function\") {\n throw new TypeError(\n \"A standards-compatible Fetch implementation is required\",\n );\n }\n const gatewayUrl = `${origin}${FETCH_PATH}`;\n\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const request = new Request(input, init);\n const requestId = createRequestId();\n let response: Response | undefined;\n let last: TianaDiagnostic;\n const emit = (\n phase: TianaDiagnostic[\"phase\"],\n fields: Pick<TianaDiagnostic, \"outerStatus\" | \"innerStatus\" | \"reason\"> = {},\n ): void => {\n last = {\n requestId,\n phase,\n time: new Date().toISOString(),\n ...(last?.outerStatus !== undefined ? { outerStatus: last.outerStatus } : {}),\n ...(last?.innerStatus !== undefined ? { innerStatus: last.innerStatus } : {}),\n ...fields,\n };\n diagnostics.set(request, last);\n if (input instanceof Request) diagnostics.set(input, last);\n if (response !== undefined) diagnostics.set(response, last);\n try {\n options.onDiagnostic?.(last);\n } catch {\n // Observation must not change the request outcome.\n }\n };\n const fail = (error: unknown): void => {\n const cancelled = request.signal.aborted;\n emit(cancelled ? \"cancelled\" : \"failed\", {\n reason: error instanceof Error ? error.name : typeof error,\n });\n if (typeof error === \"object\" && error !== null &&\n !(error instanceof TianaAuthError && diagnostics.has(error))) {\n diagnostics.set(error, last);\n }\n };\n emit(\"request_started\");\n let metadata: FetchRequestMetadata;\n let tianaToken: string;\n let frame: ReadableStream<Uint8Array> | Uint8Array<ArrayBuffer>;\n try {\n const url = new URL(request.url);\n if (url.origin !== origin) {\n throw new TypeError(\n \"Tiana Fetch request origin does not match the configured origin\",\n );\n }\n if (url.hash !== \"\") {\n throw new TypeError(\n \"Tiana Fetch request URL must not contain a fragment\",\n );\n }\n if (request.signal.aborted) {\n throw abortReason(request.signal);\n }\n // Buffer before acquiring auth so upload preparation cannot age a token.\n const body =\n protocol === \"tiana-http\" || requestBodyMode === \"buffered\"\n ? await readRequestBody(request)\n : undefined;\n tianaToken = provider\n ? await waitFor(\n Promise.resolve().then(() =>\n provider.getAccessToken({ signal: request.signal }),\n ),\n request.signal,\n )\n : staticToken!;\n if (request.signal.aborted) throw abortReason(request.signal);\n if (\n typeof tianaToken !== \"string\" ||\n tianaToken.length === 0 ||\n /[\\s\\x00-\\x1f\\x7f]/u.test(tianaToken)\n )\n throw new TypeError(\"Invalid access token\");\n metadata = requestMetadata(request, tianaToken, requestId);\n if (body !== undefined) {\n metadata = {\n ...metadata,\n ...(protocol ? { protocol } : {}),\n body_length: body.byteLength,\n };\n frame = new Uint8Array(encodeRequestFrameBytes(metadata, body));\n } else {\n frame = createRequestFrameStream(\n metadata,\n request.body,\n request.signal,\n );\n }\n } catch (error) {\n await request.body?.cancel(error).catch(() => undefined);\n fail(error);\n throw error;\n }\n const headers = new Headers();\n headers.set(\"authorization\", `Bearer ${tianaToken}`);\n headers.set(\"cache-control\", \"no-store\");\n headers.set(\"content-type\", FETCH_MEDIA_TYPE);\n headers.set(\"x-request-id\", requestId);\n const outerInit: RequestInit & { duplex?: \"half\" } = {\n method: \"POST\",\n headers,\n body: frame,\n signal: request.signal,\n cache: \"no-store\",\n credentials: \"omit\",\n redirect: \"error\",\n ...(frame instanceof ReadableStream ? { duplex: \"half\" as const } : {}),\n };\n let outer: Response;\n try {\n outer = await fetchImplementation(gatewayUrl, outerInit);\n } catch (error) {\n if (frame instanceof ReadableStream) {\n await frame.cancel(error).catch(() => undefined);\n }\n fail(error);\n throw error;\n }\n try {\n if (outer.status !== 200) {\n response = await outerErrorResponse(outer, request.url);\n emit(\"response_started\", { outerStatus: outer.status });\n emit(\"completed\");\n return response;\n }\n response = await innerResponse(\n outer,\n request,\n metadata,\n () => emit(\"completed\"),\n (error) => fail(error),\n (reason) => {\n emit(\"cancelled\", { reason: reason instanceof Error ? reason.name : typeof reason });\n },\n );\n emit(\"response_started\", { outerStatus: outer.status, innerStatus: response.status });\n if (response.body === null) emit(\"completed\");\n return response;\n } catch (error) {\n fail(error);\n throw error;\n }\n };\n}\n\n// Keep these names reachable to API extractors without exposing codec internals.\nexport type TianaOuterError = FetchError;\nexport type TianaOuterErrorCode = FetchErrorCode;\nexport type TianaOuterErrorResponse = FetchErrorResponse;\n\nexport { createTianaFiles, TianaFileError } from \"./files.js\";\nexport type {\n TianaFiles, TianaFilesOptions, TianaFile, TianaFilePage, TianaFileCapabilities,\n TianaFileGrant, TianaFileUpload, TianaFileRequest, TianaFileRequestOptions,\n TianaFilePutOptions,\n} from \"./files.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts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AAE,CAAC;gBACzB,QAAQ,GAAG,MAAM,kBAAkB,CAAC,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;gBACxD,IAAI,CAAC,kBAAkB,EAAE,EAAE,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;gBACxD,IAAI,CAAC,WAAW,CAAC,CAAC;gBAClB,OAAO,QAAQ,CAAC;YAClB,CAAC;YACD,QAAQ,GAAG,MAAM,aAAa,CAC5B,KAAK,EACL,OAAO,EACP,QAAQ,EACR,GAAG,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EACvB,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EACtB,CAAC,MAAM,EAAE,EAAE;gBACT,IAAI,CAAC,WAAW,EAAE,EAAE,MAAM,EAAE,MAAM,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,MAAM,EAAE,CAAC,CAAC;YACvF,CAAC,CACF,CAAC;YACF,IAAI,CAAC,kBAAkB,EAAE,EAAE,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YACtF,IAAI,QAAQ,CAAC,IAAI,KAAK,IAAI;gBAAE,IAAI,CAAC,WAAW,CAAC,CAAC;YAC9C,OAAO,QAAQ,CAAC;QAClB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,CAAC;YACZ,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAOD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAO9D,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC","sourcesContent":["import { diagnostics, createRequestId, type TianaDiagnostic } from \"./diagnostics.js\";\nexport { diagnosisOf, type TianaDiagnostic } from \"./diagnostics.js\";\nimport { waitFor, TianaAuthError, type TianaAuthProvider } from \"./auth.js\";\nexport { createTianaSessionAuth, TianaAuthError } from \"./auth.js\";\nexport type {\n TianaAuthProvider,\n TianaSessionAuthOptions,\n TianaSessionCredentials,\n TianaAuthErrorCode,\n} from \"./auth.js\";\nimport {\n createRequestFrameStream,\n encodeRequestFrameBytes,\n decodeResponseStream,\n} from \"./codec.js\";\nimport { protocolError } from \"./errors.js\";\nimport {\n decodeErrorResponse,\n FETCH_ERROR_MEDIA_TYPE,\n FETCH_MAX_ERROR_BODY_BYTES,\n FETCH_MEDIA_TYPE,\n FETCH_PATH,\n FETCH_MAX_REQUEST_BODY_BYTES,\n isRegisteredOuterStatus,\n type FetchError,\n type FetchErrorCode,\n type FetchErrorResponse,\n type FetchHeader,\n type FetchMethod,\n type FetchRequestMetadata,\n} from \"./protocol.js\";\n\nexport { TianaFetchProtocolError } from \"./errors.js\";\nexport type {\n FetchError,\n FetchErrorCode,\n FetchErrorResponse,\n FetchHeader,\n FetchQuotaReason,\n} from \"./protocol.js\";\n\nexport type TianaFetch = (\n input: RequestInfo | URL,\n init?: RequestInit,\n) => Promise<Response>;\n\ninterface TianaFetchBaseOptions {\n /** The sole HTTPS database origin accepted by this adapter. */\n readonly origin: string | URL;\n\n /** Select the App HTTP data socket. Omit for the native data socket. */\n readonly protocol?: \"tiana-http\";\n\n /** Buffer the request frame for browser transports without upload streaming. */\n readonly requestBodyMode?: \"stream\" | \"buffered\";\n\n /** Optional platform-compatible transport. It is invoked exactly once. */\n readonly fetch?: typeof globalThis.fetch;\n\n /** Per-request diagnostic events; callback failures do not affect Fetch. */\n readonly onDiagnostic?: (diagnostic: TianaDiagnostic) => void;\n}\n\n/** Exactly one credential source; the provider is shared across requests. */\nexport type TianaFetchOptions = TianaFetchBaseOptions &\n (\n | { readonly tianaToken: string; readonly auth?: never }\n | { readonly auth: TianaAuthProvider; readonly tianaToken?: never }\n );\n\nconst endpointHostnamePattern =\n /^ep-[0-7][0-9a-hjkmnp-tv-z]{25}\\.[a-z0-9.-]+$/;\nconst allowedMethods = new Set<FetchMethod>([\n \"GET\",\n \"HEAD\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"OPTIONS\",\n]);\n\nfunction normalizeOrigin(value: string | URL): string {\n let url: URL;\n try {\n url = value instanceof URL ? new URL(value.href) : new URL(value);\n } catch {\n throw new TypeError(\"Tiana origin must be an absolute HTTPS origin URL\");\n }\n if (\n url.protocol !== \"https:\" ||\n url.username !== \"\" ||\n url.password !== \"\" ||\n url.pathname !== \"/\" ||\n url.search !== \"\" ||\n url.hash !== \"\"\n ) {\n throw new TypeError(\"Tiana origin must be an absolute HTTPS origin URL\");\n }\n const hostname = url.hostname.toLowerCase();\n if (!endpointHostnamePattern.test(hostname)) {\n throw new TypeError(\"Tiana origin must contain a valid v1 Endpoint ID and DNS suffix\");\n }\n return url.origin;\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n\nfunction normalizedHeaders(request: Request): FetchHeader[] {\n return Array.from(request.headers.entries(), ([name, value]) => ({\n name,\n value,\n }));\n}\n\nfunction decodePercentEscapedBytes(value: string): string {\n return value.replace(\n /%([0-9a-f]{2})/gi,\n (_escape, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)),\n );\n}\n\nfunction requestMetadata(\n request: Request,\n tianaToken: string,\n requestId: string,\n): FetchRequestMetadata {\n const url = new URL(request.url);\n if (!allowedMethods.has(request.method as FetchMethod)) {\n throw new TypeError(\"Tiana Fetch does not support this request method\");\n }\n const method = request.method as FetchMethod;\n const pathQuery = `${url.pathname}${url.search}`;\n const headers = normalizedHeaders(request);\n const normalizedToken = tianaToken.toLowerCase();\n if (\n pathQuery.includes(tianaToken) ||\n decodePercentEscapedBytes(pathQuery).includes(tianaToken) ||\n headers.some(\n ({ name, value }) =>\n name.includes(normalizedToken) || value.includes(tianaToken),\n )\n ) {\n throw protocolError(\n \"The outer Tiana Token must not appear in inner Fetch metadata\",\n );\n }\n return {\n metadata_version: 1,\n request_id: requestId,\n method,\n path_query: pathQuery,\n headers,\n body_length:\n method === \"GET\" || method === \"HEAD\" || request.body === null ? 0 : null,\n };\n}\n\nasync function requireOuterHeaders(\n response: Response,\n contentType: string,\n): Promise<void> {\n try {\n if (response.headers.get(\"cache-control\") !== \"no-store\") {\n throw protocolError(\"Fetch outer response is missing Cache-Control: no-store\");\n }\n if (response.headers.get(\"content-type\") !== contentType) {\n throw protocolError(\"Fetch outer response has an invalid Content-Type\");\n }\n const contentEncoding = response.headers.get(\"content-encoding\");\n if (contentEncoding !== null && contentEncoding !== \"identity\") {\n throw protocolError(\"Fetch outer response has an invalid Content-Encoding\");\n }\n if (response.redirected) {\n throw protocolError(\"Fetch outer response must not follow redirects\");\n }\n } catch (error) {\n await response.body?.cancel(error).catch(() => undefined);\n throw error;\n }\n}\n\nasync function readBoundedBody(\n body: ReadableStream<Uint8Array> | null,\n maximum: number,\n): Promise<Uint8Array> {\n if (body === null) {\n throw protocolError(\"Fetch outer response body is missing\");\n }\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n try {\n for (;;) {\n const result = await reader.read();\n if (result.done) {\n break;\n }\n if (result.value.byteLength === 0) {\n continue;\n }\n length += result.value.byteLength;\n if (length > maximum) {\n throw protocolError(\"Fetch outer response body exceeds the SDK bound\");\n }\n chunks.push(result.value);\n }\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n throw error;\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\nasync function readRequestBody(request: Request): Promise<Uint8Array> {\n if (request.signal.aborted) throw abortReason(request.signal);\n let onAbort: () => void = () => undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(abortReason(request.signal));\n request.signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n const body = new Uint8Array(await Promise.race([request.arrayBuffer(), aborted]));\n if (request.signal.aborted) throw abortReason(request.signal);\n if (body.byteLength > FETCH_MAX_REQUEST_BODY_BYTES) throw protocolError(\"Fetch body exceeds the SDK bound\");\n return body;\n } finally {\n request.signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction responseWithUrl(response: Response, url: string): Response {\n try {\n Object.defineProperty(response, \"url\", {\n configurable: true,\n enumerable: false,\n value: url,\n });\n } catch {\n // URL is supplemental metadata. Fetch body/status/header semantics remain\n // correct on runtimes that do not permit defining an own URL property.\n }\n return response;\n}\n\nasync function outerErrorResponse(\n outer: Response,\n requestUrl: string,\n): Promise<Response> {\n if (!isRegisteredOuterStatus(outer.status)) {\n await outer.body?.cancel().catch(() => undefined);\n throw protocolError(\"Fetch outer response status is not registered\");\n }\n await requireOuterHeaders(outer, FETCH_ERROR_MEDIA_TYPE);\n if (outer.status === 405 && outer.headers.get(\"allow\") !== \"POST\") {\n await outer.body?.cancel().catch(() => undefined);\n throw protocolError(\"Fetch 405 response is missing Allow: POST\");\n }\n const body = await readBoundedBody(outer.body, FETCH_MAX_ERROR_BODY_BYTES);\n decodeErrorResponse(body, outer.status);\n return responseWithUrl(\n new Response(new Uint8Array(body), {\n status: outer.status,\n statusText: outer.statusText,\n headers: new Headers(outer.headers),\n }),\n requestUrl,\n );\n}\n\nfunction innerHeaders(headers: readonly FetchHeader[]): Headers {\n const result = new Headers();\n for (const { name, value } of headers) {\n result.append(name, value);\n }\n return result;\n}\n\nasync function innerResponse(\n outer: Response,\n request: Request,\n metadata: FetchRequestMetadata,\n onBodyComplete: () => void,\n onBodyError: (error: unknown) => void,\n onBodyCancel: (reason: unknown) => void,\n): Promise<Response> {\n await requireOuterHeaders(outer, FETCH_MEDIA_TYPE);\n if (outer.body === null) {\n throw protocolError(\"Fetch TFS1 response body is missing\");\n }\n const decoded = await decodeResponseStream(outer.body, {\n requestId: metadata.request_id,\n method: metadata.method,\n onBodyComplete,\n onBodyError,\n onBodyCancel,\n });\n return responseWithUrl(\n new Response(decoded.body, {\n status: decoded.metadata.status,\n statusText: decoded.metadata.status_text,\n headers: innerHeaders(decoded.metadata.headers),\n }),\n request.url,\n );\n}\n\n/**\n * Create a standard Fetch-compatible adapter for one exact Tiana database\n * origin. The returned function performs exactly one outer request and never\n * retries automatically.\n */\nexport function createTianaFetch(options: TianaFetchOptions): TianaFetch {\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"Tiana Fetch options are required\");\n }\n if (options.protocol !== undefined && options.protocol !== \"tiana-http\") {\n throw new TypeError(\"Unsupported Tiana Fetch protocol\");\n }\n const protocol = options.protocol;\n const requestBodyMode = options.requestBodyMode ?? \"stream\";\n if (requestBodyMode !== \"stream\" && requestBodyMode !== \"buffered\") {\n throw new TypeError(\"requestBodyMode must be either stream or buffered\");\n }\n const origin = normalizeOrigin(options.origin);\n const provider = options.auth;\n const staticToken = options.tianaToken;\n if (\n provider !== undefined\n ? staticToken !== undefined ||\n typeof provider?.getAccessToken !== \"function\"\n : typeof staticToken !== \"string\" || staticToken.length === 0\n ) {\n throw new TypeError(\"Exactly one of tianaToken or auth is required\");\n }\n const fetchImplementation =\n options.fetch ?? globalThis.fetch?.bind(globalThis);\n if (typeof fetchImplementation !== \"function\") {\n throw new TypeError(\n \"A standards-compatible Fetch implementation is required\",\n );\n }\n const gatewayUrl = `${origin}${FETCH_PATH}`;\n\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const request = new Request(input, init);\n const requestId = createRequestId();\n let response: Response | undefined;\n let last: TianaDiagnostic;\n const emit = (\n phase: TianaDiagnostic[\"phase\"],\n fields: Pick<TianaDiagnostic, \"outerStatus\" | \"innerStatus\" | \"reason\"> = {},\n ): void => {\n last = {\n requestId,\n phase,\n time: new Date().toISOString(),\n ...(last?.outerStatus !== undefined ? { outerStatus: last.outerStatus } : {}),\n ...(last?.innerStatus !== undefined ? { innerStatus: last.innerStatus } : {}),\n ...fields,\n };\n diagnostics.set(request, last);\n if (input instanceof Request) diagnostics.set(input, last);\n if (response !== undefined) diagnostics.set(response, last);\n try {\n options.onDiagnostic?.(last);\n } catch {\n // Observation must not change the request outcome.\n }\n };\n const fail = (error: unknown): void => {\n const cancelled = request.signal.aborted;\n emit(cancelled ? \"cancelled\" : \"failed\", {\n reason: error instanceof Error ? error.name : typeof error,\n });\n if (typeof error === \"object\" && error !== null &&\n !(error instanceof TianaAuthError && diagnostics.has(error))) {\n diagnostics.set(error, last);\n }\n };\n emit(\"request_started\");\n let metadata: FetchRequestMetadata;\n let tianaToken: string;\n let frame: ReadableStream<Uint8Array> | Uint8Array<ArrayBuffer>;\n try {\n const url = new URL(request.url);\n if (url.origin !== origin) {\n throw new TypeError(\n \"Tiana Fetch request origin does not match the configured origin\",\n );\n }\n if (url.hash !== \"\") {\n throw new TypeError(\n \"Tiana Fetch request URL must not contain a fragment\",\n );\n }\n if (request.signal.aborted) {\n throw abortReason(request.signal);\n }\n // Buffer before acquiring auth so upload preparation cannot age a token.\n const body =\n protocol === \"tiana-http\" || requestBodyMode === \"buffered\"\n ? await readRequestBody(request)\n : undefined;\n tianaToken = provider\n ? await waitFor(\n Promise.resolve().then(() =>\n provider.getAccessToken({ signal: request.signal }),\n ),\n request.signal,\n )\n : staticToken!;\n if (request.signal.aborted) throw abortReason(request.signal);\n if (\n typeof tianaToken !== \"string\" ||\n tianaToken.length === 0 ||\n /[\\s\\x00-\\x1f\\x7f]/u.test(tianaToken)\n )\n throw new TypeError(\"Invalid access token\");\n metadata = requestMetadata(request, tianaToken, requestId);\n if (body !== undefined) {\n metadata = {\n ...metadata,\n ...(protocol ? { protocol } : {}),\n body_length: body.byteLength,\n };\n frame = new Uint8Array(encodeRequestFrameBytes(metadata, body));\n } else {\n frame = createRequestFrameStream(\n metadata,\n request.body,\n request.signal,\n );\n }\n } catch (error) {\n await request.body?.cancel(error).catch(() => undefined);\n fail(error);\n throw error;\n }\n const headers = new Headers();\n headers.set(\"authorization\", `Bearer ${tianaToken}`);\n headers.set(\"cache-control\", \"no-store\");\n headers.set(\"content-type\", FETCH_MEDIA_TYPE);\n headers.set(\"x-request-id\", requestId);\n const outerInit: RequestInit & { duplex?: \"half\" } = {\n method: \"POST\",\n headers,\n body: frame,\n signal: request.signal,\n cache: \"no-store\",\n credentials: \"omit\",\n redirect: \"error\",\n ...(frame instanceof ReadableStream ? { duplex: \"half\" as const } : {}),\n };\n let outer: Response;\n try {\n outer = await fetchImplementation(gatewayUrl, outerInit);\n } catch (error) {\n if (frame instanceof ReadableStream) {\n await frame.cancel(error).catch(() => undefined);\n }\n fail(error);\n throw error;\n }\n try {\n if (outer.status !== 200) {\n response = await outerErrorResponse(outer, request.url);\n emit(\"response_started\", { outerStatus: outer.status });\n emit(\"completed\");\n return response;\n }\n response = await innerResponse(\n outer,\n request,\n metadata,\n () => emit(\"completed\"),\n (error) => fail(error),\n (reason) => {\n emit(\"cancelled\", { reason: reason instanceof Error ? reason.name : typeof reason });\n },\n );\n emit(\"response_started\", { outerStatus: outer.status, innerStatus: response.status });\n if (response.body === null) emit(\"completed\");\n return response;\n } catch (error) {\n fail(error);\n throw error;\n }\n };\n}\n\n// Keep these names reachable to API extractors without exposing codec internals.\nexport type TianaOuterError = FetchError;\nexport type TianaOuterErrorCode = FetchErrorCode;\nexport type TianaOuterErrorResponse = FetchErrorResponse;\n\nexport { createTianaFiles, TianaFileError } from \"./files.js\";\nexport type {\n TianaFiles, TianaFilesOptions, TianaFile, TianaFilePage, TianaFileCapabilities,\n TianaFileGrant, TianaFileUpload, TianaFileRequest, TianaFileRequestOptions,\n TianaFilePutOptions,\n} from \"./files.js\";\n\nexport { createTianaLocation, TianaLocationError } from './location.js';\nexport type { TianaLocation, TianaLocationOptions, TianaLocationRequestOptions, TianaLocationErrorCode, TianaPosition } from './location.js';\n"]}
@@ -0,0 +1,14 @@
1
+ Object.defineProperty(window,'__tianaLocationCreateWechatSDK',{configurable:true,writable:true,value:function(){
2
+ const listeners=[];
3
+ const doc=new Proxy(window.document,{get(target,key){
4
+ if(key==='addEventListener')return (type,listener,options)=>{listeners.push([type,listener,options]);target.addEventListener(type,listener,options)};
5
+ const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;
6
+ }});
7
+ const scope={document:doc,get WeixinJSBridge(){return window.WeixinJSBridge},get __wxjs_environment(){return window.__wxjs_environment}};
8
+ let wx;
9
+ (function(){
10
+ ((e,n)=>{"function"==typeof define&&(define.amd||define.cmd)?define(function(){return n(e)}):n(e,!0)})(this,function(r,e){var a,c,n,i,t,o,s,d,l,u,p,f,m,g,h,S,y,I,v,_,w,T;if(!r.jWeixin)return a={config:"preVerifyJSAPI",onMenuShareTimeline:"menu:share:timeline",onMenuShareAppMessage:"menu:share:appmessage",onMenuShareQQ:"menu:share:qq",onMenuShareWeibo:"menu:share:weiboApp",onMenuShareQZone:"menu:share:QZone",previewImage:"imagePreview",getLocation:"geoLocation",openProductSpecificView:"openProductViewWithPid",addCard:"batchAddCard",openCard:"batchViewCard",chooseWXPay:"getBrandWCPayRequest",openEnterpriseRedPacket:"getRecevieBizHongBaoRequest",startSearchBeacons:"startMonitoringBeacons",stopSearchBeacons:"stopMonitoringBeacons",onSearchBeacons:"onBeaconsInRange",consumeAndShareCard:"consumedShareCard",openAddress:"editAddress"},c=(()=>{var e,n={};for(e in a)n[a[e]]=e;return n})(),i=(n=r.document).title,t=navigator.userAgent.toLowerCase(),f=navigator.platform.toLowerCase(),o=!(!f.match("mac")&&!f.match("win")),s=-1!=t.indexOf("wxdebugger"),d=-1!=t.indexOf("micromessenger"),l=-1!=t.indexOf("android"),u=-1!=t.indexOf("iphone")||-1!=t.indexOf("ipad"),p=(f=t.match(/micromessenger\/(\d+\.\d+\.\d+)/)||t.match(/micromessenger\/(\d+\.\d+)/))?f[1]:"",m={initStartTime:L(),initEndTime:0,preVerifyStartTime:0,preVerifyEndTime:0},g={version:1,appId:"",initTime:0,preVerifyTime:0,networkType:"",isPreVerifyOk:1,systemType:u?1:l?2:-1,clientVersion:p,url:encodeURIComponent(location.href)},h={},S={_completes:[]},y={state:0,data:{}},O(function(){m.initEndTime=L()}),I=!1,v=[],_={config:function(e){C("config",h=e);var o=!1!==h.check;O(function(){if(o)k(a.config,{verifyJsApiList:A(h.jsApiList),verifyOpenTagList:A(h.openTagList)},(S._complete=function(e){m.preVerifyEndTime=L(),y.state=1,y.data=e},S.success=function(e){g.isPreVerifyOk=0},S.fail=function(e){S._fail?S._fail(e):y.state=-1},(t=S._completes).push(function(){B()}),S.complete=function(e){for(var n=0,i=t.length;n<i;++n)t[n]();S._completes=[]},S)),m.preVerifyStartTime=L();else{y.state=1;for(var e=S._completes,n=0,i=e.length;n<i;++n)e[n]();S._completes=[]}var t}),_.invoke||(_.invoke=function(e,n,i){r.WeixinJSBridge&&WeixinJSBridge.invoke(e,P(n),i)},_.on=function(e,n){r.WeixinJSBridge&&WeixinJSBridge.on(e,n)})},ready:function(e){(0!=y.state||(S._completes.push(e),!d&&h.debug))&&e()},error:function(e){p<"6.0.2"||(-1==y.state?e(y.data):S._fail=e)},checkJsApi:function(e){k("checkJsApi",{jsApiList:A(e.jsApiList)},(e._complete=function(e){l&&(i=e.checkResult)&&(e.checkResult=JSON.parse(i));var n,i=e,t=i.checkResult;for(n in t){var o=c[n];o&&(t[o]=t[n],delete t[n])}},e))},onMenuShareTimeline:function(e){M(a.onMenuShareTimeline,{complete:function(){k("shareTimeline",{title:e.title||i,desc:e.title||i,img_url:e.imgUrl||"",link:e.link||location.href,type:e.type||"link",data_url:e.dataUrl||""},e)}},e)},onMenuShareAppMessage:function(n){M(a.onMenuShareAppMessage,{complete:function(e){"favorite"===e.scene?k("sendAppMessage",{title:n.title||i,desc:n.desc||"",link:n.link||location.href,img_url:n.imgUrl||"",type:n.type||"link",data_url:n.dataUrl||""}):k("sendAppMessage",{title:n.title||i,desc:n.desc||"",link:n.link||location.href,img_url:n.imgUrl||"",type:n.type||"link",data_url:n.dataUrl||""},n)}},n)},onMenuShareQQ:function(e){M(a.onMenuShareQQ,{complete:function(){k("shareQQ",{title:e.title||i,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},onMenuShareWeibo:function(e){M(a.onMenuShareWeibo,{complete:function(){k("shareWeiboApp",{title:e.title||i,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},onMenuShareQZone:function(e){M(a.onMenuShareQZone,{complete:function(){k("shareQZone",{title:e.title||i,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},updateTimelineShareData:function(e){k("updateTimelineShareData",{title:e.title,link:e.link,imgUrl:e.imgUrl},e)},updateAppMessageShareData:function(e){k("updateAppMessageShareData",{title:e.title,desc:e.desc,link:e.link,imgUrl:e.imgUrl},e)},startRecord:function(e){k("startRecord",{},e)},stopRecord:function(e){k("stopRecord",{},e)},onVoiceRecordEnd:function(e){M("onVoiceRecordEnd",e)},playVoice:function(e){k("playVoice",{localId:e.localId},e)},pauseVoice:function(e){k("pauseVoice",{localId:e.localId},e)},stopVoice:function(e){k("stopVoice",{localId:e.localId},e)},onVoicePlayEnd:function(e){M("onVoicePlayEnd",e)},uploadVoice:function(e){k("uploadVoice",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},downloadVoice:function(e){k("downloadVoice",{serverId:e.serverId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},translateVoice:function(e){k("translateVoice",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},chooseImage:function(e){k("chooseImage",{scene:"1|2",count:e.count||9,sizeType:e.sizeType||["original","compressed"],sourceType:e.sourceType||["album","camera"]},(e._complete=function(e){if(l){var n=e.localIds;try{n&&(e.localIds=JSON.parse(n))}catch(e){}}},e))},getLocation:function(e){},getLocation:function(e){e=e||{},k(a.getLocation,{type:e.type||"wgs84"},(e._complete=function(e){delete e.type},e))},previewImage:function(e){k(a.previewImage,{current:e.current,urls:e.urls},e)},uploadImage:function(e){k("uploadImage",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},downloadImage:function(e){k("downloadImage",{serverId:e.serverId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},getLocalImgData:function(e){!1===I?(I=!0,k("getLocalImgData",{localId:e.localId},(e._complete=function(e){var n;I=!1,0<v.length&&(n=v.shift(),wx.getLocalImgData(n))},e))):v.push(e)},getNetworkType:function(e){k("getNetworkType",{},(e._complete=function(e){var n=e,e=n.errMsg,i=(n.errMsg="getNetworkType:ok",n.subtype);if(delete n.subtype,i)n.networkType=i;else{var i=e.indexOf(":"),t=e.substring(i+1);switch(t){case"wifi":case"edge":case"wwan":n.networkType=t;break;default:n.errMsg="getNetworkType:fail"}}},e))},openLocation:function(e){k("openLocation",{latitude:e.latitude,longitude:e.longitude,name:e.name||"",address:e.address||"",scale:e.scale||28,infoUrl:e.infoUrl||""},e)},hideOptionMenu:function(e){k("hideOptionMenu",{},e)},showOptionMenu:function(e){k("showOptionMenu",{},e)},closeWindow:function(e){k("closeWindow",{},e=e||{})},hideMenuItems:function(e){k("hideMenuItems",{menuList:e.menuList},e)},showMenuItems:function(e){k("showMenuItems",{menuList:e.menuList},e)},hideAllNonBaseMenuItem:function(e){k("hideAllNonBaseMenuItem",{},e)},showAllNonBaseMenuItem:function(e){k("showAllNonBaseMenuItem",{},e)},scanQRCode:function(e){k("scanQRCode",{needResult:(e=e||{}).needResult||0,scanType:e.scanType||["qrCode","barCode"]},(e._complete=function(e){var n;u&&(n=e.resultStr)&&(n=JSON.parse(n),e.resultStr=n&&n.scan_code&&n.scan_code.scan_result)},e))},openAddress:function(e){k(a.openAddress,{},(e._complete=function(e){(e=e).postalCode=e.addressPostalCode,delete e.addressPostalCode,e.provinceName=e.proviceFirstStageName,delete e.proviceFirstStageName,e.cityName=e.addressCitySecondStageName,delete e.addressCitySecondStageName,e.countryName=e.addressCountiesThirdStageName,delete e.addressCountiesThirdStageName,e.detailInfo=e.addressDetailInfo,delete e.addressDetailInfo},e))},openProductSpecificView:function(e){k(a.openProductSpecificView,{pid:e.productId,view_type:e.viewType||0,ext_info:e.extInfo},e)},addCard:function(e){for(var n=e.cardList,i=[],t=0,o=n.length;t<o;++t){var r=n[t],r={card_id:r.cardId,card_ext:r.cardExt};i.push(r)}k(a.addCard,{card_list:i},(e._complete=function(e){if(n=e.card_list){for(var n,i=0,t=(n=JSON.parse(n)).length;i<t;++i){var o=n[i];o.cardId=o.card_id,o.cardExt=o.card_ext,o.isSuccess=!!o.is_succ,delete o.card_id,delete o.card_ext,delete o.is_succ}e.cardList=n,delete e.card_list}},e))},chooseCard:function(e){k("chooseCard",{app_id:h.appId,location_id:e.shopId||"",sign_type:e.signType||"SHA1",card_id:e.cardId||"",card_type:e.cardType||"",card_sign:e.cardSign,time_stamp:e.timestamp+"",nonce_str:e.nonceStr},(e._complete=function(e){e.cardList=e.choose_card_info,delete e.choose_card_info},e))},openCard:function(e){for(var n=e.cardList,i=[],t=0,o=n.length;t<o;++t){var r=n[t],r={card_id:r.cardId,code:r.code};i.push(r)}k(a.openCard,{card_list:i},e)},consumeAndShareCard:function(e){k(a.consumeAndShareCard,{consumedCardId:e.cardId,consumedCode:e.code},e)},chooseWXPay:function(e){k(a.chooseWXPay,x(e),e),B({jsApiName:"chooseWXPay"})},openEnterpriseRedPacket:function(e){k(a.openEnterpriseRedPacket,x(e),e)},startSearchBeacons:function(e){k(a.startSearchBeacons,{ticket:e.ticket},e)},stopSearchBeacons:function(e){k(a.stopSearchBeacons,{},e)},onSearchBeacons:function(e){M(a.onSearchBeacons,e)},openEnterpriseChat:function(e){k("openEnterpriseChat",{useridlist:e.userIds,chatname:e.groupName},e)},launchMiniProgram:function(e){k("launchMiniProgram",{targetAppId:e.targetAppId,path:(e=>{var n;if("string"==typeof e&&0<e.length)return n=e.split("?")[0],n+=".html",void 0!==(e=e.split("?")[1])?n+"?"+e:n})(e.path),envVersion:e.envVersion},e)},openBusinessView:function(e){k("openBusinessView",{businessType:e.businessType,queryString:e.queryString||"",envVersion:e.envVersion},(e._complete=function(n){if(l){var e=n.extraData;if(e)try{n.extraData=JSON.parse(e)}catch(e){n.extraData={}}}},e))},miniProgram:{navigateBack:function(e){e=e||{},O(function(){k("invokeMiniProgramAPI",{name:"navigateBack",arg:{delta:e.delta||1}},e)})},navigateTo:function(e){O(function(){k("invokeMiniProgramAPI",{name:"navigateTo",arg:{url:e.url}},e)})},redirectTo:function(e){O(function(){k("invokeMiniProgramAPI",{name:"redirectTo",arg:{url:e.url}},e)})},switchTab:function(e){O(function(){k("invokeMiniProgramAPI",{name:"switchTab",arg:{url:e.url}},e)})},reLaunch:function(e){O(function(){k("invokeMiniProgramAPI",{name:"reLaunch",arg:{url:e.url}},e)})},postMessage:function(e){O(function(){k("invokeMiniProgramAPI",{name:"postMessage",arg:e.data||{}},e)})},getEnv:function(e){O(function(){e({miniprogram:"miniprogram"===r.__wxjs_environment})})}}},w=1,T={},n.addEventListener("error",function(e){var n,i,t;l||(t=(n=e.target).tagName,i=n.src,"IMG"!=t&&"VIDEO"!=t&&"AUDIO"!=t&&"SOURCE"!=t)||-1!=i.indexOf("wxlocalresource://")&&(e.preventDefault(),e.stopPropagation(),(t=n["wx-id"])||(t=w++,n["wx-id"]=t),T[t]||(T[t]=!0,wx.ready(function(){wx.getLocalImgData({localId:i,success:function(e){n.src=e.localData}})})))},!0),n.addEventListener("load",function(e){var n;l||(n=(e=e.target).tagName,"IMG"!=n&&"VIDEO"!=n&&"AUDIO"!=n&&"SOURCE"!=n)||(n=e["wx-id"])&&(T[n]=!1)},!0),e&&(r.wx=r.jWeixin=_),_;function k(n,e,i){r.WeixinJSBridge?WeixinJSBridge.invoke(n,P(e),function(e){V(n,e,i)}):C(n,i)}function M(n,i,t){r.WeixinJSBridge?WeixinJSBridge.on(n,function(e){t&&t.trigger&&t.trigger(e),V(n,e,i)}):C(n,t||i)}function P(e){return(e=e||{}).appId=h.appId,e.verifyAppId=h.appId,e.verifySignType="sha1",e.verifyTimestamp=h.timestamp+"",e.verifyNonceStr=h.nonceStr,e.verifySignature=h.signature,e}function x(e){return{timeStamp:e.timestamp+"",nonceStr:e.nonceStr,package:e.package,paySign:e.paySign,signType:e.signType||"SHA1"}}function V(e,n,i){"openEnterpriseChat"!=e&&"openBusinessView"!==e||(n.errCode=n.err_code),delete n.err_code,delete n.err_desc,delete n.err_detail;var t=n.errMsg,e=(t||(t=n.err_msg,delete n.err_msg,t=((e,n)=>{var i,t=c[e];return t&&(e=t),t="ok",n&&(i=n.indexOf(":"),"access denied"!=(t=(t=(t=-1!=(t=-1!=(t="failed"==(t="confirm"==(t=n.substring(i+1))?"ok":t)?"fail":t).indexOf("failed_")?t.substring(7):t).indexOf("fail_")?t.substring(5):t).replace(/_/g," ")).toLowerCase())&&"no permission to execute"!=t||(t="permission denied"),""==(t="config"==e&&"function not exist"==t?"ok":t))&&(t="fail"),n=e+":"+t})(e,t),n.errMsg=t),(i=i||{})._complete&&(i._complete(n),delete i._complete),t=n.errMsg||"",h.debug&&!i.isInnerInvoke&&alert(JSON.stringify(n)),t.indexOf(":"));switch(t.substring(e+1)){case"ok":i.success&&i.success(n);break;case"cancel":i.cancel&&i.cancel(n);break;default:i.fail&&i.fail(n)}i.complete&&i.complete(n)}function A(e){if(e){for(var n=0,i=e.length;n<i;++n){var t=e[n],t=a[t];t&&(e[n]=t)}return e}}function C(e,n){var i;!h.debug||n&&n.isInnerInvoke||((i=c[e])&&(e=i),n&&n._complete&&delete n._complete,console.log('"'+e+'",',n||""))}function B(n){var i;o||s||h.debug||p<"6.0.2"||g.systemType<0||(i=new Image,g.appId=h.appId,g.initTime=m.initEndTime-m.initStartTime,g.preVerifyTime=m.preVerifyEndTime-m.preVerifyStartTime,_.getNetworkType({isInnerInvoke:!0,success:function(e){g.networkType=e.networkType;e="https://open.weixin.qq.com/sdk/report?v="+g.version+"&o="+g.isPreVerifyOk+"&s="+g.systemType+"&c="+g.clientVersion+"&a="+g.appId+"&n="+g.networkType+"&i="+g.initTime+"&p="+g.preVerifyTime+"&u="+g.url+"&jsapi_name="+(n?n.jsApiName:"");i.src=e}}))}function L(){return(new Date).getTime()}function O(e){d&&(r.WeixinJSBridge?e():n.addEventListener&&n.addEventListener("WeixinJSBridgeReady",e,!1))}});
11
+ }).call(scope);
12
+ wx=scope.wx;
13
+ return {api:wx,dispose(){for(const [type,listener,options] of listeners.splice(0))window.document.removeEventListener(type,listener,options)}};
14
+ }});
@@ -0,0 +1,35 @@
1
+ /** One-shot device location. This module has no import-time browser side effects. */
2
+ export type TianaLocationErrorCode = "PERMISSION_DENIED" | "UNAVAILABLE" | "TIMEOUT" | "ABORTED" | "UNSUPPORTED" | "CONFIGURATION" | "INVALID_RESULT" | "BUSY" | "DISPOSED";
3
+ export interface TianaPosition {
4
+ readonly latitude: number;
5
+ readonly longitude: number;
6
+ readonly accuracy: number;
7
+ /** Unix milliseconds; WeChat reports the receipt time, not a sensor timestamp. */
8
+ readonly timestamp: number;
9
+ readonly coordinateSystem: "WGS-84";
10
+ }
11
+ export interface TianaLocationRequestOptions {
12
+ readonly timeoutMs?: number;
13
+ readonly signal?: AbortSignal;
14
+ }
15
+ export interface TianaLocationOptions {
16
+ /** Platform-owned same-origin signing endpoint. AppID is server-owned. */
17
+ readonly signingUrl?: string;
18
+ /** Same-origin, pinned official JS-SDK resource, loaded only on demand. */
19
+ readonly sdkUrl?: string;
20
+ /** Original document URL, captured before SPA navigation. */
21
+ readonly entryUrl?: string;
22
+ readonly fetch?: typeof globalThis.fetch;
23
+ }
24
+ export interface TianaLocation {
25
+ getCurrentPosition(options?: TianaLocationRequestOptions): Promise<TianaPosition>;
26
+ dispose(): void;
27
+ }
28
+ export declare class TianaLocationError extends Error {
29
+ readonly code: TianaLocationErrorCode;
30
+ readonly diagnostic?: string | undefined;
31
+ constructor(code: TianaLocationErrorCode, diagnostic?: string | undefined);
32
+ }
33
+ /** Platform factories own configuration; application calls need no environment branches. */
34
+ export declare function createTianaLocation(options?: TianaLocationOptions): TianaLocation;
35
+ //# sourceMappingURL=location.d.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sBAAsB,EAC5B,UAAU,CAAC,EAAE,MAAM,YAAA,EAI7B;CACF;AA+ID,4FAA4F;AAC5F,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,oBAAyB,GACjC,aAAa,CAkTf"}
@@ -0,0 +1,371 @@
1
+ export class TianaLocationError extends Error {
2
+ code;
3
+ diagnostic;
4
+ constructor(code, diagnostic) {
5
+ super(`Device location failed (${code})`);
6
+ this.code = code;
7
+ this.diagnostic = diagnostic;
8
+ this.name = "TianaLocationError";
9
+ }
10
+ }
11
+ function record(value) {
12
+ return value !== null && typeof value === "object"
13
+ ? value
14
+ : {};
15
+ }
16
+ function nativeDiagnostic(value) {
17
+ const message = record(value).errMsg;
18
+ if (typeof message !== "string")
19
+ return "WX_CONFIG_REJECTED";
20
+ if (/invalid[\s_-]*signature/i.test(message))
21
+ return "WX_SIGNATURE_INVALID";
22
+ if (/invalid[\s_-]*(url|domain)/i.test(message))
23
+ return "WX_DOMAIN_NOT_ALLOWED";
24
+ if (/invalid[\s_-]*app[\s_-]*id/i.test(message))
25
+ return "WX_APP_ID_INVALID";
26
+ if (/permission|no[\s_-]*access/i.test(message))
27
+ return "WX_API_PERMISSION";
28
+ return "WX_CONFIG_REJECTED";
29
+ }
30
+ function numeric(value) {
31
+ if (typeof value === "number")
32
+ return value;
33
+ if (typeof value !== "string" || value.length > 64)
34
+ return NaN;
35
+ return /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(value.trim())
36
+ ? Number(value)
37
+ : NaN;
38
+ }
39
+ function position(value, wechat, started) {
40
+ const raw = record(value), fields = wechat ? raw : record(raw.coords);
41
+ const latitude = wechat ? numeric(fields.latitude) : fields.latitude;
42
+ const longitude = wechat ? numeric(fields.longitude) : fields.longitude;
43
+ const accuracy = wechat ? numeric(fields.accuracy) : fields.accuracy;
44
+ const timestamp = wechat ? Date.now() : raw.timestamp;
45
+ const invalid = (field) => {
46
+ throw new TianaLocationError("INVALID_RESULT", "RESULT_" + field + "_INVALID");
47
+ };
48
+ if (typeof latitude !== "number" ||
49
+ !Number.isFinite(latitude) ||
50
+ Math.abs(latitude) > 90)
51
+ invalid("LATITUDE");
52
+ if (typeof longitude !== "number" ||
53
+ !Number.isFinite(longitude) ||
54
+ Math.abs(longitude) > 180)
55
+ invalid("LONGITUDE");
56
+ if (typeof accuracy !== "number" ||
57
+ !Number.isFinite(accuracy) ||
58
+ accuracy < 0)
59
+ invalid("ACCURACY");
60
+ if (typeof timestamp !== "number" ||
61
+ !Number.isSafeInteger(timestamp) ||
62
+ !(timestamp >= started - 1000 && timestamp <= Date.now() + 60000))
63
+ invalid("TIMESTAMP");
64
+ return Object.freeze({
65
+ latitude: latitude,
66
+ longitude: longitude,
67
+ accuracy: accuracy,
68
+ timestamp: timestamp,
69
+ coordinateSystem: "WGS-84",
70
+ });
71
+ }
72
+ function sameOrigin(value, view) {
73
+ if (!value)
74
+ throw new TianaLocationError("CONFIGURATION", "WX_CONFIGURATION_UNAVAILABLE");
75
+ const url = new URL(value);
76
+ if (url.origin !== view.location.origin ||
77
+ !["https:", "http:"].includes(url.protocol) ||
78
+ url.username ||
79
+ url.password ||
80
+ url.search ||
81
+ url.hash)
82
+ throw new TianaLocationError("CONFIGURATION", "WX_CONFIGURATION_ORIGIN");
83
+ return url;
84
+ }
85
+ async function publicConfig(response) {
86
+ if (!response.ok)
87
+ throw new TianaLocationError("CONFIGURATION", "WX_SIGN_HTTP_FAILED");
88
+ if (!response.body)
89
+ throw new TianaLocationError("CONFIGURATION", "WX_SIGN_RESPONSE_INVALID");
90
+ const reader = response.body.getReader(), chunks = [];
91
+ let length = 0;
92
+ try {
93
+ for (;;) {
94
+ const { value, done } = await reader.read();
95
+ if (done)
96
+ break;
97
+ length += value.byteLength;
98
+ if (length > 8192) {
99
+ await reader.cancel().catch(() => undefined);
100
+ throw new TianaLocationError("CONFIGURATION", "WX_SIGN_RESPONSE_INVALID");
101
+ }
102
+ chunks.push(value);
103
+ }
104
+ }
105
+ finally {
106
+ reader.releaseLock();
107
+ }
108
+ const bytes = new Uint8Array(length);
109
+ let offset = 0;
110
+ for (const chunk of chunks) {
111
+ bytes.set(chunk, offset);
112
+ offset += chunk.byteLength;
113
+ }
114
+ return record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
115
+ }
116
+ /** Platform factories own configuration; application calls need no environment branches. */
117
+ export function createTianaLocation(options = {}) {
118
+ const view = typeof window === "undefined" ||
119
+ !window.document ||
120
+ !window.navigator ||
121
+ !window.location
122
+ ? undefined
123
+ : window;
124
+ const entryUrl = (options.entryUrl ?? view?.location.href ?? "").split("#")[0];
125
+ const transport = options.fetch ?? globalThis.fetch;
126
+ const ua = view?.navigator.userAgent ?? "";
127
+ const desktop = /Windows NT|WindowsWechat|Macintosh|MacWechat|X11/i.test(ua) &&
128
+ !/Android|iPhone|iPad|Mobile/i.test(ua);
129
+ const wechat = !!view &&
130
+ !desktop &&
131
+ (/MicroMessenger|miniProgram/i.test(ua) ||
132
+ view.__wxjs_environment === "miniprogram");
133
+ const waiters = new Set();
134
+ let disposed = false, configured, configuredRelease, pending, attempts = 0;
135
+ function prepare() {
136
+ if (configured)
137
+ return Promise.resolve(configured);
138
+ if (pending)
139
+ return pending.promise;
140
+ const abort = new AbortController();
141
+ let timer;
142
+ let stopSetup;
143
+ let releaseSDK;
144
+ const work = (async () => {
145
+ if (!view)
146
+ throw new TianaLocationError("UNSUPPORTED");
147
+ const endpoint = sameOrigin(options.signingUrl, view), scriptUrl = sameOrigin(options.sdkUrl, view), documentUrl = new URL(entryUrl);
148
+ if (documentUrl.origin !== view.location.origin ||
149
+ documentUrl.username ||
150
+ documentUrl.password)
151
+ throw new TianaLocationError("CONFIGURATION", "WX_ENTRY_URL_INVALID");
152
+ const active = () => {
153
+ if (abort.signal.aborted || disposed)
154
+ throw new TianaLocationError("CONFIGURATION", "WX_SETUP_CANCELLED");
155
+ };
156
+ const wx = await new Promise((resolve, reject) => {
157
+ const script = view.document.createElement("script");
158
+ const priorFactory = view.__tianaLocationCreateWechatSDK;
159
+ let finished = false;
160
+ if (attempts++)
161
+ scriptUrl.searchParams.set("retry", String(attempts));
162
+ script.src = scriptUrl.href;
163
+ const finish = (error, api) => {
164
+ if (finished)
165
+ return;
166
+ finished = true;
167
+ script.onload = null;
168
+ script.onerror = null;
169
+ script.remove();
170
+ abort.signal.removeEventListener("abort", cancel);
171
+ if (error)
172
+ reject(error);
173
+ else
174
+ resolve(api);
175
+ };
176
+ const cancel = () => finish(new TianaLocationError("CONFIGURATION", "WX_SDK_LOAD_CANCELLED"));
177
+ abort.signal.addEventListener("abort", cancel, { once: true });
178
+ script.onload = () => {
179
+ if (finished)
180
+ return;
181
+ try {
182
+ if (view.__tianaLocationCreateWechatSDK === priorFactory)
183
+ throw Error("SDK factory was not refreshed");
184
+ const handle = view.__tianaLocationCreateWechatSDK?.();
185
+ if (!handle || typeof handle.dispose !== "function")
186
+ throw Error("Invalid SDK factory");
187
+ releaseSDK = () => handle.dispose();
188
+ if (!handle.api ||
189
+ !["config", "ready", "error", "getLocation"].every((key) => typeof handle.api[key] === "function"))
190
+ throw Error("Invalid SDK");
191
+ finish(undefined, handle.api);
192
+ }
193
+ catch {
194
+ finish(new TianaLocationError("CONFIGURATION", "WX_SDK_LOAD_FAILED"));
195
+ }
196
+ };
197
+ script.onerror = () => finish(new TianaLocationError("CONFIGURATION", "WX_SDK_LOAD_FAILED"));
198
+ view.document.head.append(script);
199
+ });
200
+ active();
201
+ endpoint.searchParams.set("url", entryUrl);
202
+ const response = await transport(endpoint.href, {
203
+ method: "GET",
204
+ credentials: "same-origin",
205
+ cache: "no-store",
206
+ redirect: "error",
207
+ signal: abort.signal,
208
+ });
209
+ active();
210
+ const config = await publicConfig(response);
211
+ active();
212
+ if (typeof config.app_id !== "string" ||
213
+ !/^wx[a-f0-9]{16}$/i.test(config.app_id) ||
214
+ config.url !== entryUrl ||
215
+ !Number.isSafeInteger(config.timestamp) ||
216
+ config.timestamp <= 0 ||
217
+ typeof config.nonce_str !== "string" ||
218
+ config.nonce_str.length < 1 ||
219
+ config.nonce_str.length > 256 ||
220
+ typeof config.signature !== "string" ||
221
+ !/^[a-f0-9]{40}$/i.test(config.signature))
222
+ throw new TianaLocationError("CONFIGURATION", "WX_SIGN_RESPONSE_INVALID");
223
+ return await new Promise((resolve, reject) => {
224
+ wx.ready(() => {
225
+ if (!abort.signal.aborted && !disposed)
226
+ resolve(wx);
227
+ });
228
+ wx.error((error) => reject(new TianaLocationError("CONFIGURATION", nativeDiagnostic(error))));
229
+ wx.config({
230
+ debug: false,
231
+ appId: config.app_id,
232
+ timestamp: config.timestamp,
233
+ nonceStr: config.nonce_str,
234
+ signature: config.signature,
235
+ jsApiList: ["getLocation"],
236
+ });
237
+ });
238
+ })();
239
+ const deadline = new Promise((_resolve, reject) => {
240
+ stopSetup = () => reject(new TianaLocationError(disposed ? "DISPOSED" : "CONFIGURATION", "WX_SETUP_CANCELLED"));
241
+ abort.signal.addEventListener("abort", stopSetup, { once: true });
242
+ timer = setTimeout(() => {
243
+ reject(new TianaLocationError("CONFIGURATION", "WX_SETUP_TIMEOUT"));
244
+ abort.abort();
245
+ }, 10000);
246
+ });
247
+ const promise = Promise.race([work, deadline])
248
+ .catch((error) => {
249
+ releaseSDK?.();
250
+ throw error instanceof TianaLocationError
251
+ ? error
252
+ : new TianaLocationError("CONFIGURATION", "WX_CONFIGURATION_FAILED");
253
+ })
254
+ .finally(() => {
255
+ clearTimeout(timer);
256
+ if (stopSetup)
257
+ abort.signal.removeEventListener("abort", stopSetup);
258
+ });
259
+ const attempt = { promise, abort };
260
+ pending = attempt;
261
+ void promise.then((wx) => {
262
+ if (!disposed) {
263
+ configured = wx;
264
+ configuredRelease = releaseSDK;
265
+ }
266
+ if (pending === attempt)
267
+ pending = undefined;
268
+ }, () => {
269
+ if (pending === attempt)
270
+ pending = undefined;
271
+ });
272
+ return promise;
273
+ }
274
+ return Object.freeze({
275
+ getCurrentPosition(request = {}) {
276
+ const timeout = request.timeoutMs ?? 20000;
277
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120000)
278
+ return Promise.reject(new TypeError("timeoutMs must be an integer from 1 to 120000"));
279
+ if (disposed)
280
+ return Promise.reject(new TianaLocationError("DISPOSED"));
281
+ if (request.signal?.aborted)
282
+ return Promise.reject(new TianaLocationError("ABORTED"));
283
+ if (!view)
284
+ return Promise.reject(new TianaLocationError("UNSUPPORTED"));
285
+ if (waiters.size >= 32)
286
+ return Promise.reject(new TianaLocationError("BUSY"));
287
+ const started = Date.now();
288
+ return new Promise((resolve, reject) => {
289
+ let active = true;
290
+ const finish = (error, value) => {
291
+ if (!active)
292
+ return;
293
+ active = false;
294
+ clearTimeout(timer);
295
+ request.signal?.removeEventListener("abort", cancel);
296
+ waiters.delete(fail);
297
+ if (error)
298
+ reject(error);
299
+ else
300
+ resolve(value);
301
+ };
302
+ const fail = (error) => finish(error);
303
+ const cancel = () => fail(new TianaLocationError("ABORTED"));
304
+ const timer = setTimeout(() => fail(new TianaLocationError("TIMEOUT")), timeout);
305
+ waiters.add(fail);
306
+ request.signal?.addEventListener("abort", cancel, { once: true });
307
+ const accept = (value) => {
308
+ if (!active)
309
+ return;
310
+ try {
311
+ finish(undefined, position(value, wechat, started));
312
+ }
313
+ catch (error) {
314
+ fail(error instanceof TianaLocationError
315
+ ? error
316
+ : new TianaLocationError("INVALID_RESULT"));
317
+ }
318
+ };
319
+ void (async () => {
320
+ if (request.signal?.aborted) {
321
+ cancel();
322
+ return;
323
+ }
324
+ if (wechat) {
325
+ const wx = await prepare();
326
+ if (!active)
327
+ return;
328
+ wx.getLocation({
329
+ type: "wgs84",
330
+ success: accept,
331
+ cancel: () => fail(new TianaLocationError("ABORTED")),
332
+ fail: (error) => {
333
+ const message = record(error).errMsg;
334
+ fail(new TianaLocationError(typeof message === "string" &&
335
+ /deny|denied|auth|permission/i.test(message)
336
+ ? "PERMISSION_DENIED"
337
+ : "UNAVAILABLE"));
338
+ },
339
+ });
340
+ }
341
+ else {
342
+ const geo = view.navigator.geolocation;
343
+ if (!geo) {
344
+ fail(new TianaLocationError("UNSUPPORTED"));
345
+ return;
346
+ }
347
+ geo.getCurrentPosition(accept, (error) => fail(new TianaLocationError({
348
+ 1: "PERMISSION_DENIED",
349
+ 2: "UNAVAILABLE",
350
+ 3: "TIMEOUT",
351
+ }[error.code] ?? "UNAVAILABLE")), { enableHighAccuracy: true, maximumAge: 0, timeout });
352
+ }
353
+ })().catch((error) => fail(error instanceof TianaLocationError
354
+ ? error
355
+ : new TianaLocationError("UNAVAILABLE")));
356
+ });
357
+ },
358
+ dispose() {
359
+ if (disposed)
360
+ return;
361
+ disposed = true;
362
+ for (const fail of waiters)
363
+ fail(new TianaLocationError("DISPOSED"));
364
+ pending?.abort.abort();
365
+ configuredRelease?.();
366
+ configuredRelease = undefined;
367
+ configured = undefined;
368
+ },
369
+ });
370
+ }
371
+ //# sourceMappingURL=location.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"location.js","sourceRoot":"","sources":["../src/location.ts"],"names":[],"mappings":"AAsCA,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAEhC,IAAI;IACJ,UAAU;IAFrB,YACW,IAA4B,EAC5B,UAAmB;QAE5B,KAAK,CAAC,2BAA2B,IAAI,GAAG,CAAC,CAAC;oBAHjC,IAAI;0BACJ,UAAU;QAGnB,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAiBD,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAChD,CAAC,CAAE,KAAiC;QACpC,CAAC,CAAC,EAAE,CAAC;AACT,CAAC;AACD,SAAS,gBAAgB,CAAC,KAAc;IACtC,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC;IACrC,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,oBAAoB,CAAC;IAC7D,I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N,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC;wBACvC,IAAI,CAAC,GAAG,EAAE,CAAC;4BACT,IAAI,CAAC,IAAI,kBAAkB,CAAC,aAAa,CAAC,CAAC,CAAC;4BAC5C,OAAO;wBACT,CAAC;wBACD,GAAG,CAAC,kBAAkB,CACpB,MAAM,EACN,CAAC,KAAK,EAAE,EAAE,CACR,IAAI,CACF,IAAI,kBAAkB,CAElB;4BACE,CAAC,EAAE,mBAAmB;4BACtB,CAAC,EAAE,aAAa;4BAChB,CAAC,EAAE,SAAS;yBAEf,CAAC,KAAK,CAAC,IAAiB,CAAC,IAAI,aAAa,CAC5C,CACF,EACH,EAAE,kBAAkB,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,CACrD,CAAC;oBACJ,CAAC;gBACH,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CACnB,IAAI,CACF,KAAK,YAAY,kBAAkB;oBACjC,CAAC,CAAC,KAAK;oBACP,CAAC,CAAC,IAAI,kBAAkB,CAAC,aAAa,CAAC,CAC1C,CACF,CAAC;YACJ,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAO;YACL,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,KAAK,MAAM,IAAI,IAAI,OAAO;gBAAE,IAAI,CAAC,IAAI,kBAAkB,CAAC,UAAU,CAAC,CAAC,CAAC;YACrE,OAAO,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;YACvB,iBAAiB,EAAE,EAAE,CAAC;YACtB,iBAAiB,GAAG,SAAS,CAAC;YAC9B,UAAU,GAAG,SAAS,CAAC;QACzB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/** One-shot device location. This module has no import-time browser side effects. */\nexport type TianaLocationErrorCode =\n | \"PERMISSION_DENIED\"\n | \"UNAVAILABLE\"\n | \"TIMEOUT\"\n | \"ABORTED\"\n | \"UNSUPPORTED\"\n | \"CONFIGURATION\"\n | \"INVALID_RESULT\"\n | \"BUSY\"\n | \"DISPOSED\";\nexport interface TianaPosition {\n readonly latitude: number;\n readonly longitude: number;\n readonly accuracy: number;\n /** Unix milliseconds; WeChat reports the receipt time, not a sensor timestamp. */\n readonly timestamp: number;\n readonly coordinateSystem: \"WGS-84\";\n}\nexport interface TianaLocationRequestOptions {\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n}\nexport interface TianaLocationOptions {\n /** Platform-owned same-origin signing endpoint. AppID is server-owned. */\n readonly signingUrl?: string;\n /** Same-origin, pinned official JS-SDK resource, loaded only on demand. */\n readonly sdkUrl?: string;\n /** Original document URL, captured before SPA navigation. */\n readonly entryUrl?: string;\n readonly fetch?: typeof globalThis.fetch;\n}\nexport interface TianaLocation {\n getCurrentPosition(\n options?: TianaLocationRequestOptions,\n ): Promise<TianaPosition>;\n dispose(): void;\n}\nexport class TianaLocationError extends Error {\n constructor(\n readonly code: TianaLocationErrorCode,\n readonly diagnostic?: string,\n ) {\n super(`Device location failed (${code})`);\n this.name = \"TianaLocationError\";\n }\n}\ntype Callback = (value?: unknown) => void;\ninterface WechatAPI {\n config(value: object): void;\n ready(callback: Callback): void;\n error(callback: Callback): void;\n getLocation(value: {\n type: \"wgs84\";\n success: Callback;\n fail: Callback;\n cancel: Callback;\n }): void;\n}\ntype ClientWindow = Window & {\n __tianaLocationCreateWechatSDK?: () => { api: WechatAPI; dispose(): void };\n __wxjs_environment?: unknown;\n};\nfunction record(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === \"object\"\n ? (value as Record<string, unknown>)\n : {};\n}\nfunction nativeDiagnostic(value: unknown): string {\n const message = record(value).errMsg;\n if (typeof message !== \"string\") return \"WX_CONFIG_REJECTED\";\n if (/invalid[\\s_-]*signature/i.test(message)) return \"WX_SIGNATURE_INVALID\";\n if (/invalid[\\s_-]*(url|domain)/i.test(message))\n return \"WX_DOMAIN_NOT_ALLOWED\";\n if (/invalid[\\s_-]*app[\\s_-]*id/i.test(message)) return \"WX_APP_ID_INVALID\";\n if (/permission|no[\\s_-]*access/i.test(message)) return \"WX_API_PERMISSION\";\n return \"WX_CONFIG_REJECTED\";\n}\nfunction numeric(value: unknown): number {\n if (typeof value === \"number\") return value;\n if (typeof value !== \"string\" || value.length > 64) return NaN;\n return /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?$/.test(value.trim())\n ? Number(value)\n : NaN;\n}\nfunction position(\n value: unknown,\n wechat: boolean,\n started: number,\n): TianaPosition {\n const raw = record(value),\n fields = wechat ? raw : record(raw.coords);\n const latitude = wechat ? numeric(fields.latitude) : fields.latitude;\n const longitude = wechat ? numeric(fields.longitude) : fields.longitude;\n const accuracy = wechat ? numeric(fields.accuracy) : fields.accuracy;\n const timestamp = wechat ? Date.now() : raw.timestamp;\n const invalid = (field: string): never => {\n throw new TianaLocationError(\n \"INVALID_RESULT\",\n \"RESULT_\" + field + \"_INVALID\",\n );\n };\n if (\n typeof latitude !== \"number\" ||\n !Number.isFinite(latitude) ||\n Math.abs(latitude) > 90\n )\n invalid(\"LATITUDE\");\n if (\n typeof longitude !== \"number\" ||\n !Number.isFinite(longitude) ||\n Math.abs(longitude) > 180\n )\n invalid(\"LONGITUDE\");\n if (\n typeof accuracy !== \"number\" ||\n !Number.isFinite(accuracy) ||\n accuracy < 0\n )\n invalid(\"ACCURACY\");\n if (\n typeof timestamp !== \"number\" ||\n !Number.isSafeInteger(timestamp) ||\n !(timestamp >= started - 1000 && timestamp <= Date.now() + 60000)\n )\n invalid(\"TIMESTAMP\");\n return Object.freeze({\n latitude: latitude as number,\n longitude: longitude as number,\n accuracy: accuracy as number,\n timestamp: timestamp as number,\n coordinateSystem: \"WGS-84\",\n });\n}\nfunction sameOrigin(value: string | undefined, view: ClientWindow): URL {\n if (!value)\n throw new TianaLocationError(\n \"CONFIGURATION\",\n \"WX_CONFIGURATION_UNAVAILABLE\",\n );\n const url = new URL(value);\n if (\n url.origin !== view.location.origin ||\n ![\"https:\", \"http:\"].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n )\n throw new TianaLocationError(\"CONFIGURATION\", \"WX_CONFIGURATION_ORIGIN\");\n return url;\n}\nasync function publicConfig(\n response: Response,\n): Promise<Record<string, unknown>> {\n if (!response.ok)\n throw new TianaLocationError(\"CONFIGURATION\", \"WX_SIGN_HTTP_FAILED\");\n if (!response.body)\n throw new TianaLocationError(\"CONFIGURATION\", \"WX_SIGN_RESPONSE_INVALID\");\n const reader = response.body.getReader(),\n chunks: Uint8Array[] = [];\n let length = 0;\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n length += value.byteLength;\n if (length > 8192) {\n await reader.cancel().catch(() => undefined);\n throw new TianaLocationError(\n \"CONFIGURATION\",\n \"WX_SIGN_RESPONSE_INVALID\",\n );\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return record(\n JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)),\n );\n}\n/** Platform factories own configuration; application calls need no environment branches. */\nexport function createTianaLocation(\n options: TianaLocationOptions = {},\n): TianaLocation {\n const view =\n typeof window === \"undefined\" ||\n !window.document ||\n !window.navigator ||\n !window.location\n ? undefined\n : (window as ClientWindow);\n const entryUrl = (options.entryUrl ?? view?.location.href ?? \"\").split(\n \"#\",\n )[0]!;\n const transport = options.fetch ?? globalThis.fetch;\n const ua = view?.navigator.userAgent ?? \"\";\n const desktop =\n /Windows NT|WindowsWechat|Macintosh|MacWechat|X11/i.test(ua) &&\n !/Android|iPhone|iPad|Mobile/i.test(ua);\n const wechat =\n !!view &&\n !desktop &&\n (/MicroMessenger|miniProgram/i.test(ua) ||\n view.__wxjs_environment === \"miniprogram\");\n const waiters = new Set<(error: TianaLocationError) => void>();\n let disposed = false,\n configured: WechatAPI | undefined,\n configuredRelease: (() => void) | undefined,\n pending:\n | { promise: Promise<WechatAPI>; abort: AbortController }\n | undefined,\n attempts = 0;\n function prepare(): Promise<WechatAPI> {\n if (configured) return Promise.resolve(configured);\n if (pending) return pending.promise;\n const abort = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let stopSetup: (() => void) | undefined;\n let releaseSDK: (() => void) | undefined;\n const work = (async () => {\n if (!view) throw new TianaLocationError(\"UNSUPPORTED\");\n const endpoint = sameOrigin(options.signingUrl, view),\n scriptUrl = sameOrigin(options.sdkUrl, view),\n documentUrl = new URL(entryUrl);\n if (\n documentUrl.origin !== view.location.origin ||\n documentUrl.username ||\n documentUrl.password\n )\n throw new TianaLocationError(\"CONFIGURATION\", \"WX_ENTRY_URL_INVALID\");\n const active = (): void => {\n if (abort.signal.aborted || disposed)\n throw new TianaLocationError(\"CONFIGURATION\", \"WX_SETUP_CANCELLED\");\n };\n const wx = await new Promise<WechatAPI>((resolve, reject) => {\n const script = view.document.createElement(\"script\");\n const priorFactory = view.__tianaLocationCreateWechatSDK;\n let finished = false;\n if (attempts++) scriptUrl.searchParams.set(\"retry\", String(attempts));\n script.src = scriptUrl.href;\n const finish = (error?: TianaLocationError, api?: WechatAPI): void => {\n if (finished) return;\n finished = true;\n script.onload = null;\n script.onerror = null;\n script.remove();\n abort.signal.removeEventListener(\"abort\", cancel);\n if (error) reject(error);\n else resolve(api!);\n };\n const cancel = (): void =>\n finish(\n new TianaLocationError(\"CONFIGURATION\", \"WX_SDK_LOAD_CANCELLED\"),\n );\n abort.signal.addEventListener(\"abort\", cancel, { once: true });\n script.onload = () => {\n if (finished) return;\n try {\n if (view.__tianaLocationCreateWechatSDK === priorFactory)\n throw Error(\"SDK factory was not refreshed\");\n const handle = view.__tianaLocationCreateWechatSDK?.();\n if (!handle || typeof handle.dispose !== \"function\")\n throw Error(\"Invalid SDK factory\");\n releaseSDK = () => handle.dispose();\n if (\n !handle.api ||\n ![\"config\", \"ready\", \"error\", \"getLocation\"].every(\n (key) =>\n typeof (handle.api as unknown as Record<string, unknown>)[\n key\n ] === \"function\",\n )\n )\n throw Error(\"Invalid SDK\");\n finish(undefined, handle.api);\n } catch {\n finish(\n new TianaLocationError(\"CONFIGURATION\", \"WX_SDK_LOAD_FAILED\"),\n );\n }\n };\n script.onerror = () =>\n finish(new TianaLocationError(\"CONFIGURATION\", \"WX_SDK_LOAD_FAILED\"));\n view.document.head.append(script);\n });\n active();\n endpoint.searchParams.set(\"url\", entryUrl);\n const response = await transport(endpoint.href, {\n method: \"GET\",\n credentials: \"same-origin\",\n cache: \"no-store\",\n redirect: \"error\",\n signal: abort.signal,\n });\n active();\n const config = await publicConfig(response);\n active();\n if (\n typeof config.app_id !== \"string\" ||\n !/^wx[a-f0-9]{16}$/i.test(config.app_id) ||\n config.url !== entryUrl ||\n !Number.isSafeInteger(config.timestamp) ||\n (config.timestamp as number) <= 0 ||\n typeof config.nonce_str !== \"string\" ||\n config.nonce_str.length < 1 ||\n config.nonce_str.length > 256 ||\n typeof config.signature !== \"string\" ||\n !/^[a-f0-9]{40}$/i.test(config.signature)\n )\n throw new TianaLocationError(\n \"CONFIGURATION\",\n \"WX_SIGN_RESPONSE_INVALID\",\n );\n return await new Promise<WechatAPI>((resolve, reject) => {\n wx.ready(() => {\n if (!abort.signal.aborted && !disposed) resolve(wx);\n });\n wx.error((error) =>\n reject(\n new TianaLocationError(\"CONFIGURATION\", nativeDiagnostic(error)),\n ),\n );\n wx.config({\n debug: false,\n appId: config.app_id,\n timestamp: config.timestamp,\n nonceStr: config.nonce_str,\n signature: config.signature,\n jsApiList: [\"getLocation\"],\n });\n });\n })();\n const deadline = new Promise<never>((_resolve, reject) => {\n stopSetup = () =>\n reject(\n new TianaLocationError(\n disposed ? \"DISPOSED\" : \"CONFIGURATION\",\n \"WX_SETUP_CANCELLED\",\n ),\n );\n abort.signal.addEventListener(\"abort\", stopSetup, { once: true });\n timer = setTimeout(() => {\n reject(new TianaLocationError(\"CONFIGURATION\", \"WX_SETUP_TIMEOUT\"));\n abort.abort();\n }, 10000);\n });\n const promise = Promise.race([work, deadline])\n .catch((error) => {\n releaseSDK?.();\n throw error instanceof TianaLocationError\n ? error\n : new TianaLocationError(\"CONFIGURATION\", \"WX_CONFIGURATION_FAILED\");\n })\n .finally(() => {\n clearTimeout(timer);\n if (stopSetup) abort.signal.removeEventListener(\"abort\", stopSetup);\n });\n const attempt = { promise, abort };\n pending = attempt;\n void promise.then(\n (wx) => {\n if (!disposed) {\n configured = wx;\n configuredRelease = releaseSDK;\n }\n if (pending === attempt) pending = undefined;\n },\n () => {\n if (pending === attempt) pending = undefined;\n },\n );\n return promise;\n }\n return Object.freeze({\n getCurrentPosition(\n request: TianaLocationRequestOptions = {},\n ): Promise<TianaPosition> {\n const timeout = request.timeoutMs ?? 20000;\n if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120000)\n return Promise.reject(\n new TypeError(\"timeoutMs must be an integer from 1 to 120000\"),\n );\n if (disposed) return Promise.reject(new TianaLocationError(\"DISPOSED\"));\n if (request.signal?.aborted)\n return Promise.reject(new TianaLocationError(\"ABORTED\"));\n if (!view) return Promise.reject(new TianaLocationError(\"UNSUPPORTED\"));\n if (waiters.size >= 32)\n return Promise.reject(new TianaLocationError(\"BUSY\"));\n const started = Date.now();\n return new Promise<TianaPosition>((resolve, reject) => {\n let active = true;\n const finish = (\n error?: TianaLocationError,\n value?: TianaPosition,\n ): void => {\n if (!active) return;\n active = false;\n clearTimeout(timer);\n request.signal?.removeEventListener(\"abort\", cancel);\n waiters.delete(fail);\n if (error) reject(error);\n else resolve(value!);\n };\n const fail = (error: TianaLocationError): void => finish(error);\n const cancel = (): void => fail(new TianaLocationError(\"ABORTED\"));\n const timer = setTimeout(\n () => fail(new TianaLocationError(\"TIMEOUT\")),\n timeout,\n );\n waiters.add(fail);\n request.signal?.addEventListener(\"abort\", cancel, { once: true });\n const accept: Callback = (value) => {\n if (!active) return;\n try {\n finish(undefined, position(value, wechat, started));\n } catch (error) {\n fail(\n error instanceof TianaLocationError\n ? error\n : new TianaLocationError(\"INVALID_RESULT\"),\n );\n }\n };\n void (async () => {\n if (request.signal?.aborted) {\n cancel();\n return;\n }\n if (wechat) {\n const wx = await prepare();\n if (!active) return;\n wx.getLocation({\n type: \"wgs84\",\n success: accept,\n cancel: () => fail(new TianaLocationError(\"ABORTED\")),\n fail: (error) => {\n const message = record(error).errMsg;\n fail(\n new TianaLocationError(\n typeof message === \"string\" &&\n /deny|denied|auth|permission/i.test(message)\n ? \"PERMISSION_DENIED\"\n : \"UNAVAILABLE\",\n ),\n );\n },\n });\n } else {\n const geo = view.navigator.geolocation;\n if (!geo) {\n fail(new TianaLocationError(\"UNSUPPORTED\"));\n return;\n }\n geo.getCurrentPosition(\n accept,\n (error) =>\n fail(\n new TianaLocationError(\n (\n {\n 1: \"PERMISSION_DENIED\",\n 2: \"UNAVAILABLE\",\n 3: \"TIMEOUT\",\n } as const\n )[error.code as 1 | 2 | 3] ?? \"UNAVAILABLE\",\n ),\n ),\n { enableHighAccuracy: true, maximumAge: 0, timeout },\n );\n }\n })().catch((error) =>\n fail(\n error instanceof TianaLocationError\n ? error\n : new TianaLocationError(\"UNAVAILABLE\"),\n ),\n );\n });\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n for (const fail of waiters) fail(new TianaLocationError(\"DISPOSED\"));\n pending?.abort.abort();\n configuredRelease?.();\n configuredRelease = undefined;\n configured = undefined;\n },\n });\n}\n"]}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@tianacloud/serverless",
3
- "version": "0.1.0-beta.4",
3
+ "version": "0.2.0",
4
4
  "description": "Tiana Fetch-over-HTTPS transport for serverless and edge JavaScript runtimes",
5
5
  "type": "module",
6
6
  "publishConfig": {
7
7
  "access": "public",
8
8
  "registry": "https://registry.npmjs.org/",
9
- "tag": "next"
9
+ "tag": "latest"
10
10
  },
11
11
  "sideEffects": false,
12
12
  "license": "Apache-2.0",
@@ -27,10 +27,15 @@
27
27
  "types": "./dist/index.d.ts",
28
28
  "import": "./dist/index.js",
29
29
  "default": "./dist/index.js"
30
+ },
31
+ "./codec": {
32
+ "types": "./dist/codec-public.d.ts",
33
+ "import": "./dist/codec-public.js",
34
+ "default": "./dist/codec-public.js"
30
35
  }
31
36
  },
32
37
  "scripts": {
33
- "build": "node scripts/clean.mjs && tsc -p tsconfig.json",
38
+ "build": "node scripts/clean.mjs && tsc -p tsconfig.json && node scripts/copy-browser-assets.mjs",
34
39
  "typecheck": "tsc -p tsconfig.json --noEmit",
35
40
  "test:types": "pnpm run build && tsc -p tests/types/tsconfig.json",
36
41
  "test": "pnpm run test:node",