@raster-app/sdk 0.1.0-canary-fd0f8dd → 0.1.0-rc.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 CHANGED
@@ -1,21 +1,190 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Monogram
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Raster
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,33 +1,21 @@
1
1
  # @raster-app/sdk
2
2
 
3
3
  A client for the [Raster](https://raster.app) REST API: sign-in, sessions, assets, libraries,
4
- search and image helpers.
5
-
6
- ## Documentation
7
-
8
- [raster.app/docs](https://raster.app/docs)
9
-
10
- ## Requirements
11
-
12
- - A browser, or Node.js 24 or later
13
- - No dependencies
14
-
15
- ## Installation
4
+ search and image helpers. It runs in browsers and in Node 24 and later. The blurhash
5
+ placeholder draws on a `document`, so outside a browser it returns null.
16
6
 
17
7
  ```sh
18
8
  npm install @raster-app/sdk
19
9
  ```
20
10
 
21
- For React, install [`@raster-app/react`](https://www.npmjs.com/package/@raster-app/react) instead.
22
- It includes this package.
23
-
24
- ## Usage
11
+ A React host installs [`@raster-app/react`](https://www.npmjs.com/package/@raster-app/react)
12
+ instead, which re-exports all of this package.
25
13
 
26
14
  ```ts
27
15
  import { createRasterClient, localStorageCredentialStore } from '@raster-app/sdk'
28
16
 
29
17
  const raster = createRasterClient({
30
- host: { name: 'My App', openExternal: (url) => window.open(url, '_blank') },
18
+ host: { name: 'Sanity', openExternal: (url) => window.open(url, '_blank') },
31
19
  credentials: localStorageCredentialStore(),
32
20
  })
33
21
 
@@ -45,7 +33,7 @@ const libraries = await raster.libraries.list({ organizationId: 'acme' })
45
33
  const assets = await raster.assets.list({ organizationId: 'acme', libraryId: 'lib-1' })
46
34
  ```
47
35
 
48
- ### The host
36
+ ## The host
49
37
 
50
38
  `createRasterClient` takes what differs from one host to the next:
51
39
 
@@ -57,10 +45,10 @@ const assets = await raster.assets.list({ organizationId: 'acme', libraryId: 'li
57
45
 
58
46
  Each client has its own session, so several can run on one page.
59
47
 
60
- ### Signing in
48
+ ## Signing in
61
49
 
62
50
  `auth.signInWithDevice` runs the OAuth device grant (RFC 8628), which works in every host,
63
- including a plugin's sandboxed iframe. `onCode` receives the code to show the user while the
51
+ including a Figma plugin's iframe. `onCode` receives the code to show the user while the
64
52
  consent page opens in their browser, and the promise settles once they approve.
65
53
  `auth.connect({ apiKey })` connects an organization API key. Either way, `/me` checks the
66
54
  credential before it is stored, so a bad key fails the call.
@@ -70,20 +58,19 @@ works in one organization passes `scope: 'org'`, which has the user pick exactly
70
58
  organization's id as `organizationId`. Any other grant, of another organization or of the whole
71
59
  account, then fails with `ORGANIZATION_MISMATCH` and leaves the saved credential as it was.
72
60
 
73
- ### Errors
61
+ ## Errors
74
62
 
75
63
  A call to Raster that fails rejects with a `RasterApiError`. Branch on its `code`, and show the
76
64
  user `toUserMessage(error)`.
77
65
 
78
- ### Images
66
+ ## Images
79
67
 
80
68
  `getThumbUrl(asset)` picks a thumbnail from the asset's `sizes`, `getPreviewUrl(asset)` a larger
81
69
  size for an asset shown large, `getFullSizeUrl(asset)` returns the full-size image, and
82
70
  `getBlurhashPlaceholder(asset)` a data URL to paint while any of them loads. Each URL carries the
83
- asset's content version, so a cache never shows a replaced file. The placeholder draws on a
84
- `document`, so outside a browser it returns null.
71
+ asset's content version, so a cache never shows a replaced file.
85
72
 
86
- ### File sizes and dates
73
+ ## File sizes and dates
87
74
 
88
75
  These show file sizes and dates as the Raster app does: decimal units, so 1 MB is 1,000,000
89
76
  bytes, and `en-US` dates.
@@ -94,7 +81,3 @@ bytes, and `en-US` dates.
94
81
  - `formatDate(asset.created)` gives the date, `formatDateLong` adds the weekday and time, and
95
82
  `formatRelativeTime` reads "just now", "5m ago", "3h ago" or "2d ago" within a week, then the
96
83
  date. Each takes a `Date` or Unix milliseconds, and returns an empty string for null.
97
-
98
- ## License
99
-
100
- MIT
@@ -16,13 +16,13 @@ export interface CredentialStore {
16
16
  export interface RasterHost {
17
17
  /**
18
18
  * The OAuth `client_name`, which Raster's consent page reads as `Connect {name}` and
19
- * Connected apps lists. It names the app being connected, since the user reaches that page
20
- * from Raster.
19
+ * Connected apps lists. It names the app being connected — "Figma", "Sanity" — since the
20
+ * user reaches that page from Raster.
21
21
  */
22
22
  name: string;
23
23
  /**
24
24
  * Open a URL in the user's browser, as the device flow does for its consent page: through
25
- * `window.open` in a page, or the host's own API in a sandbox without one.
25
+ * `figma.openExternal` in a Figma plugin's sandbox, or `window.open` in a CMS plugin.
26
26
  *
27
27
  * Typed `void`, which any return type satisfies, so `(url) => window.open(url)` and an
28
28
  * async function both fit. The SDK never awaits it.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"","sourcesContent":["import type { StoredCredentials } from '../types/session.js'\n\n/**\n * Where a host keeps the Raster credential. Async, because a Figma plugin reaches\n * `figma.clientStorage` only through a message to its sandbox.\n *\n * The credential holds bearer tokens in plain text, so it is as private as the store:\n * `localStorage` exposes it to every script on the origin.\n */\nexport interface CredentialStore {\n\t/** Null when nothing has been saved yet. */\n\tload(): Promise<StoredCredentials | null>\n\tsave(credentials: StoredCredentials): Promise<void>\n\tclear(): Promise<void>\n}\n\n/** The host application the SDK is running inside. */\nexport interface RasterHost {\n\t/**\n\t * The OAuth `client_name`, which Raster's consent page reads as `Connect {name}` and\n\t * Connected apps lists. It names the app being connected, since the user reaches that page\n\t * from Raster.\n\t */\n\tname: string\n\t/**\n\t * Open a URL in the user's browser, as the device flow does for its consent page: through\n\t * `window.open` in a page, or the host's own API in a sandbox without one.\n\t *\n\t * Typed `void`, which any return type satisfies, so `(url) => window.open(url)` and an\n\t * async function both fit. The SDK never awaits it.\n\t */\n\topenExternal(url: string): void\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"","sourcesContent":["import type { StoredCredentials } from '../types/session.js'\n\n/**\n * Where a host keeps the Raster credential. Async, because a Figma plugin reaches\n * `figma.clientStorage` only through a message to its sandbox.\n *\n * The credential holds bearer tokens in plain text, so it is as private as the store:\n * `localStorage` exposes it to every script on the origin.\n */\nexport interface CredentialStore {\n\t/** Null when nothing has been saved yet. */\n\tload(): Promise<StoredCredentials | null>\n\tsave(credentials: StoredCredentials): Promise<void>\n\tclear(): Promise<void>\n}\n\n/** The host application the SDK is running inside. */\nexport interface RasterHost {\n\t/**\n\t * The OAuth `client_name`, which Raster's consent page reads as `Connect {name}` and\n\t * Connected apps lists. It names the app being connected — \"Figma\", \"Sanity\" — since the\n\t * user reaches that page from Raster.\n\t */\n\tname: string\n\t/**\n\t * Open a URL in the user's browser, as the device flow does for its consent page: through\n\t * `figma.openExternal` in a Figma plugin's sandbox, or `window.open` in a CMS plugin.\n\t *\n\t * Typed `void`, which any return type satisfies, so `(url) => window.open(url)` and an\n\t * async function both fit. The SDK never awaits it.\n\t */\n\topenExternal(url: string): void\n}\n"]}
@@ -3,8 +3,8 @@ import { type StoredCredentials } from '../types/session.js';
3
3
  import type { AuthContext } from './http.js';
4
4
  /**
5
5
  * The credential a client holds, and everything that keeps it valid. Each
6
- * `createRasterClient` has its own, so clients on one page, such as one per workspace, never
7
- * share a token.
6
+ * `createRasterClient` has its own, so clients on one page, such as one per Sanity Studio
7
+ * workspace, never share a token.
8
8
  */
9
9
  export interface SessionStore {
10
10
  /** The credentials in memory. `undefined` until `hydrate()` has run. */
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/auth/session.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAEN,UAAU,EAEV,gBAAgB,GAChB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE3D,8FAA8F;AAC9F,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAA;AAElC,6FAA6F;AAC7F,MAAM,YAAY,GAAG,oBAAoB,CAAA;AAEzC;;;;;GAKG;AACH,KAAK,UAAU,eAAe,CAAI,OAAyB;IAC1D,MAAM,KAAK,GAAG,UAAU,CAAC,SAAS,EAAE,KAAK,CAAA;IACzC,IAAI,CAAC,KAAK;QAAE,OAAO,OAAO,EAAE,CAAA;IAC5B,IAAI,OAAO,GAAG,KAAK,CAAA;IACnB,IAAI,CAAC;QACJ,OAAO,MAAM,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,GAAG,EAAE;YAC7C,OAAO,GAAG,IAAI,CAAA;YACd,OAAO,OAAO,EAAE,CAAA;QACjB,CAAC,CAAC,CAAA;IACH,CAAC;IAAC,OAAO,MAAM,EAAE,CAAC;QACjB,IAAI,OAAO;YAAE,MAAM,MAAM,CAAA;QACzB,OAAO,OAAO,EAAE,CAAA;IACjB,CAAC;AACF,CAAC;AAED;;;GAGG;AACH,SAAS,SAAS,CAAC,MAAc;IAChC,IAAI,IAAI,GAAG,mBAAmB,CAAA;IAC9B,KAAK,MAAM,IAAI,IAAI,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QACrD,IAAI,GAAG,CAAC,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,G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YAAY,CAAC,OAAO,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAA;YAC1D,IAAI,OAAO,KAAK,KAAK,QAAQ;gBAAE,OAAO,KAAK,CAAA;YAE3C,MAAM,IAAI,GAAG,OAAO,CAAA;YACpB,UAAU,KAAV,UAAU,GAAK,eAAe,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CACvF,GAAG,EAAE;gBACJ,UAAU,GAAG,IAAI,CAAA;YAClB,CAAC,CACD,EAAA;YACD,OAAO,UAAU,CAAA;QAClB,CAAC;QAED;;;WAGG;QACH,KAAK,CAAC,OAAO;YACZ,MAAM,KAAK,GAAG,OAAO,EAAE,KAAK,IAAI,IAAI,CAAA;YACpC,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC,CAAA;YACvB,IAAI,KAAK,KAAK,IAAI;gBAAE,MAAM,aAAa,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;QACrE,CAAC;KACD,CAAA;AACF,CAAC","sourcesContent":["import type { CredentialStore } from '../adapters/index.js'\nimport { RasterApiError } from '../api/errors.js'\nimport {\n\ttype OAuthSession,\n\tSIGNED_OUT,\n\ttype StoredCredentials,\n\temptyCredentials,\n} from '../types/session.js'\nimport type { AuthContext } from './http.js'\nimport { refreshSession, revokeSession } from './tokens.js'\n\n/** Refresh this far ahead of `expiresAt`, so a token is never presented right at its edge. */\nconst EXPIRY_MARGIN_MS = 60 * 1000\n\n/** One name for every client on the origin: refreshes are rare, so queueing costs little. */\nconst REFRESH_LOCK = 'raster-sdk:refresh'\n\n/**\n * Run a refresh under a lock every tab on the origin shares, so two tabs never rotate one\n * refresh token at once. Without the Web Locks API, or where it refuses the request (an\n * opaque origin such as Figma's plugin iframe), it runs unlocked: re-reading the store\n * first then narrows that race rather than closing it.\n */\nasync function withRefreshLock<T>(refresh: () => Promise<T>): Promise<T> {\n\tconst locks = globalThis.navigator?.locks\n\tif (!locks) return refresh()\n\tlet granted = false\n\ttry {\n\t\treturn await locks.request(REFRESH_LOCK, () => {\n\t\t\tgranted = true\n\t\t\treturn refresh()\n\t\t})\n\t} catch (caught) {\n\t\tif (granted) throw caught\n\t\treturn refresh()\n\t}\n}\n\n/**\n * A 64-bit FNV-1a digest of an API key: the same for the same key, different for another in\n * practice, and too short to recover the key from.\n */\nfunction keyDigest(apiKey: string): string {\n\tlet hash = 0xcbf29ce484222325n\n\tfor (const byte of new TextEncoder().encode(apiKey)) {\n\t\thash = ((hash ^ BigInt(byte)) * 0x100000001b3n) & 0xffffffffffffffffn\n\t}\n\treturn hash.toString(36)\n}\n\n/**\n * The credential a client holds, and everything that keeps it valid. Each\n * `createRasterClient` has its own, so clients on one page, such as one per workspace, never\n * share a token.\n */\nexport interface SessionStore {\n\t/** The credentials in memory. `undefined` until `hydrate()` has run. */\n\tcurrent(): StoredCredentials | undefined\n\t/** Load from the `CredentialStore`. Idempotent; safe to await more than once. */\n\thydrate(): Promise<StoredCredentials>\n\t/** Persist, then replace in memory. A failed write changes nothing and rejects with its error. */\n\tsave(credentials: StoredCredentials): Promise<void>\n\t/** Called on every change — a sign-in, a token refresh, a sign-out. */\n\tsubscribe(listener: (credentials: StoredCredentials) => void): () => void\n\tisSignedIn(): boolean\n\t/** Whether there is any credential at all (a session or an API key). */\n\tisConfigured(): boolean\n\tcredentialIdentity(): string | null\n\tgetAccessToken(options?: { rejected?: string }): Promise<string>\n\tsignOut(): Promise<void>\n}\n\nexport function createSessionStore(options: {\n\tcredentials: CredentialStore\n\tauth: AuthContext\n}): SessionStore {\n\tconst { credentials: store, auth } = options\n\n\tlet current: StoredCredentials | undefined\n\t/** What `save` is writing, which memory takes only once the store has it. */\n\tlet writing: StoredCredentials | undefined\n\tlet hydrating: Promise<StoredCredentials> | null = null\n\tlet refreshing: Promise<string> | null = null\n\tconst listeners = new Set<(credentials: StoredCredentials) => void>()\n\n\tfunction emit(next: StoredCredentials): void {\n\t\tcurrent = next\n\t\tfor (const listener of listeners) listener(next)\n\t}\n\n\t/**\n\t * Write first, then change memory and tell listeners. A failed write leaves memory as it\n\t * was and rejects with the store's own error, so a sign-in or sign-out the store never took\n\t * is not in use either.\n\t */\n\tasync function save(next: StoredCredentials): Promise<void> {\n\t\twriting = next\n\t\ttry {\n\t\t\tawait store.save(next)\n\t\t} finally {\n\t\t\tif (writing === next) writing = undefined\n\t\t}\n\t\temit(next)\n\t}\n\n\t/**\n\t * Read the store, filling in the fields a credential saved before they existed lacks:\n\t * a missing `oauth` is not `null`, so it would read as signed in.\n\t */\n\tasync function load(): Promise<StoredCredentials | null> {\n\t\tconst stored = await store.load()\n\t\treturn stored === null ? null : { ...emptyCredentials(), ...stored }\n\t}\n\n\t/** Signed-out credentials that keep this install's registration (see `clientId`). */\n\tfunction signedOut(): StoredCredentials {\n\t\treturn { ...SIGNED_OUT, clientId: current?.clientId ?? null }\n\t}\n\n\t/** Whether the stored session, or the one being written, is still the one a refresh started from. */\n\tfunction isSameSession(session: OAuthSession): boolean {\n\t\treturn (writing ?? current)?.oauth?.refreshToken === session.refreshToken\n\t}\n\n\t/**\n\t * Single-flight: a provider and a first request can both call this on mount, and two\n\t * concurrent loads would race to `emit` — the later one winning even if it read staler\n\t * data.\n\t */\n\tfunction hydrate(): Promise<StoredCredentials> {\n\t\thydrating ??= load()\n\t\t\t.then((loaded) => {\n\t\t\t\tconst next = loaded ?? emptyCredentials()\n\t\t\t\temit(next)\n\t\t\t\treturn next\n\t\t\t})\n\t\t\t.catch((caught) => {\n\t\t\t\t// Clear the cached promise so a transient read failure can be retried rather\n\t\t\t\t// than poisoning every later call.\n\t\t\t\thydrating = null\n\t\t\t\tthrow caught\n\t\t\t})\n\t\treturn hydrating\n\t}\n\n\tasync function refresh(session: OAuthSession): Promise<OAuthSession> {\n\t\tlet next: OAuthSession\n\t\ttry {\n\t\t\tnext = await refreshSession(auth, session)\n\t\t} catch (caught) {\n\t\t\t// The connection is gone — revoked under Connected apps, membership lost, or the\n\t\t\t// token was spent already. Only signing in again fixes that, so drop the dead\n\t\t\t// session now rather than fail every request with it.\n\t\t\tif (caught instanceof RasterApiError && caught.code === 'invalid_grant') {\n\t\t\t\tif (isSameSession(session)) await save(signedOut())\n\t\t\t\tthrow new RasterApiError(\n\t\t\t\t\t'Your Raster session has ended. Sign in again.',\n\t\t\t\t\t'SESSION_EXPIRED',\n\t\t\t\t\t401\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow caught\n\t\t}\n\n\t\t// The old refresh token died the moment this one was minted, so memory takes the new\n\t\t// one first and keeps it even if the write fails; the token is handed out only once\n\t\t// written. Skipped if the session changed under us (signed out, or signed in again)\n\t\t// while the refresh was in flight — that newer session must not be clobbered.\n\t\tif (current !== undefined && isSameSession(session)) {\n\t\t\tconst rotated = { ...current, oauth: next }\n\t\t\temit(rotated)\n\t\t\tawait store.save(rotated)\n\t\t}\n\t\treturn next\n\t}\n\n\t/**\n\t * The bearer the credentials can send as they stand, or the session to refresh first:\n\t * its token is about to expire, or is the `rejected` one a request just got a 401 with.\n\t */\n\tfunction tokenOrStale(\n\t\tcredentials: StoredCredentials | undefined,\n\t\trejected: string | undefined\n\t): string | OAuthSession {\n\t\tif (credentials === undefined || credentials.oauth === null) {\n\t\t\tconst apiKey = credentials?.apiKey\n\t\t\tif (!apiKey) throw new RasterApiError('Sign in to Raster first.', 'NOT_SIGNED_IN', 401)\n\t\t\treturn apiKey\n\t\t}\n\n\t\tconst { oauth } = credentials\n\t\tconst fresh = Date.now() < oauth.expiresAt - EXPIRY_MARGIN_MS\n\t\t// A rejected token that has already been replaced here: another request refreshed\n\t\t// first, so this one can simply use the new token.\n\t\treturn fresh && oauth.accessToken !== rejected ? oauth.accessToken : oauth\n\t}\n\n\t/**\n\t * Refresh unless another tab sharing the store got there first. Its copy wins — it may\n\t * have rotated the token, signed out, or signed in as somebody else — unless this tab\n\t * changed its own credentials while waiting. A store that reads back null is unreadable\n\t * (blocked storage), not signed out.\n\t */\n\tasync function refreshLatest(\n\t\tfrom: StoredCredentials | undefined,\n\t\trejected: string | undefined\n\t): Promise<string> {\n\t\tconst stored = await load()\n\t\tif (\n\t\t\tstored !== null &&\n\t\t\tcurrent === from &&\n\t\t\tstored.oauth?.refreshToken !== from?.oauth?.refreshToken\n\t\t) {\n\t\t\temit(stored)\n\t\t}\n\t\tconst found = tokenOrStale(current, rejected)\n\t\treturn typeof found === 'string' ? found : (await refresh(found)).accessToken\n\t}\n\n\treturn {\n\t\tcurrent() {\n\t\t\treturn current\n\t\t},\n\n\t\thydrate,\n\n\t\tsave,\n\n\t\tsubscribe(listener) {\n\t\t\tlisteners.add(listener)\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener)\n\t\t\t}\n\t\t},\n\n\t\tisSignedIn() {\n\t\t\treturn current !== undefined && current.oauth !== null\n\t\t},\n\n\t\tisConfigured() {\n\t\t\treturn (\n\t\t\t\tcurrent !== undefined &&\n\t\t\t\t(current.oauth !== null || (typeof current.apiKey === 'string' && current.apiKey !== ''))\n\t\t\t)\n\t\t},\n\n\t\t/**\n\t\t * Identifies WHOSE credential is in use, so a caller can tell a token refresh apart\n\t\t * from a different account signing in. Stable across refreshes and reloads, and new\n\t\t * with every sign-in, even one through the same client (see `OAuthSession.signInId`).\n\t\t * A session saved before sign-ins had an id falls back to its client. An API key is\n\t\t * named by its digest, so the key itself never lands in a cache key or a log.\n\t\t */\n\t\tcredentialIdentity() {\n\t\t\tif (current === undefined) return null\n\t\t\tconst { oauth, apiKey } = current\n\t\t\tif (oauth !== null) return `oauth:${oauth.signInId ?? oauth.clientId}`\n\t\t\treturn apiKey === null ? null : `key:${keyDigest(apiKey)}`\n\t\t},\n\n\t\t/**\n\t\t * The bearer to send: the API key, or the session's access token, refreshed first when\n\t\t * it is about to expire or is the `rejected` one. Refreshes are single-flight, because\n\t\t * the server treats a second use of a rotated refresh token as theft and revokes the\n\t\t * whole connection; tabs sharing a store share one too (`refreshLatest`).\n\t\t */\n\t\tasync getAccessToken(tokenOptions = {}) {\n\t\t\tif (current === undefined) await hydrate()\n\n\t\t\tconst found = tokenOrStale(current, tokenOptions.rejected)\n\t\t\tif (typeof found === 'string') return found\n\n\t\t\tconst from = current\n\t\t\trefreshing ??= withRefreshLock(() => refreshLatest(from, tokenOptions.rejected)).finally(\n\t\t\t\t() => {\n\t\t\t\t\trefreshing = null\n\t\t\t\t}\n\t\t\t)\n\t\t\treturn refreshing\n\t\t},\n\n\t\t/**\n\t\t * Sign out: clear the session, and revoke it in Raster (best-effort — it is gone\n\t\t * locally either way, and a failed revoke must not leave the user stuck signed in).\n\t\t */\n\t\tasync signOut() {\n\t\t\tconst oauth = current?.oauth ?? null\n\t\t\tawait save(signedOut())\n\t\t\tif (oauth !== null) await revokeSession(auth, oauth).catch(() => {})\n\t\t},\n\t}\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/auth/session.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAEN,UAAU,EAEV,gBAAgB,GAChB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE3D,8FAA8F;AAC9F,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAA;AAElC,6FAA6F;AAC7F,MAAM,YAAY,GAAG,oBAAoB,CAAA;AAEzC;;;;;GAKG;AACH,KAAK,UAAU,eAAe,CAAI,OAAyB;IAC1D,MAAM,KAAK,GAAG,UAAU,CAAC,SAAS,EAAE,KAAK,CAAA;IACzC,IAAI,CAAC,KAAK;QAAE,OAAO,OAAO,EAAE,CAAA;IAC5B,IAAI,OAAO,GAAG,KAAK,CAAA;IACnB,IAAI,CAAC;QACJ,OAAO,MAAM,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,GAAG,EAAE;YAC7C,OAAO,GAAG,IAAI,C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C,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAA;YACjC,IAAI,KAAK,KAAK,IAAI;gBAAE,OAAO,SAAS,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAA;YACtE,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,SAAS,CAAC,MAAM,CAAC,EAAE,CAAA;QAC3D,CAAC;QAED;;;;;WAKG;QACH,KAAK,CAAC,cAAc,CAAC,YAAY,GAAG,EAAE;YACrC,IAAI,OAAO,KAAK,SAAS;gBAAE,MAAM,OAAO,EAAE,CAAA;YAE1C,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAA;YAC1D,IAAI,OAAO,KAAK,KAAK,QAAQ;gBAAE,OAAO,KAAK,CAAA;YAE3C,MAAM,IAAI,GAAG,OAAO,CAAA;YACpB,UAAU,KAAV,UAAU,GAAK,eAAe,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CACvF,GAAG,EAAE;gBACJ,UAAU,GAAG,IAAI,CAAA;YAClB,CAAC,CACD,EAAA;YACD,OAAO,UAAU,CAAA;QAClB,CAAC;QAED;;;WAGG;QACH,KAAK,CAAC,OAAO;YACZ,MAAM,KAAK,GAAG,OAAO,EAAE,KAAK,IAAI,IAAI,CAAA;YACpC,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC,CAAA;YACvB,IAAI,KAAK,KAAK,IAAI;gBAAE,MAAM,aAAa,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;QACrE,CAAC;KACD,CAAA;AACF,CAAC","sourcesContent":["import type { CredentialStore } from '../adapters/index.js'\nimport { RasterApiError } from '../api/errors.js'\nimport {\n\ttype OAuthSession,\n\tSIGNED_OUT,\n\ttype StoredCredentials,\n\temptyCredentials,\n} from '../types/session.js'\nimport type { AuthContext } from './http.js'\nimport { refreshSession, revokeSession } from './tokens.js'\n\n/** Refresh this far ahead of `expiresAt`, so a token is never presented right at its edge. */\nconst EXPIRY_MARGIN_MS = 60 * 1000\n\n/** One name for every client on the origin: refreshes are rare, so queueing costs little. */\nconst REFRESH_LOCK = 'raster-sdk:refresh'\n\n/**\n * Run a refresh under a lock every tab on the origin shares, so two tabs never rotate one\n * refresh token at once. Without the Web Locks API, or where it refuses the request (an\n * opaque origin such as Figma's plugin iframe), it runs unlocked: re-reading the store\n * first then narrows that race rather than closing it.\n */\nasync function withRefreshLock<T>(refresh: () => Promise<T>): Promise<T> {\n\tconst locks = globalThis.navigator?.locks\n\tif (!locks) return refresh()\n\tlet granted = false\n\ttry {\n\t\treturn await locks.request(REFRESH_LOCK, () => {\n\t\t\tgranted = true\n\t\t\treturn refresh()\n\t\t})\n\t} catch (caught) {\n\t\tif (granted) throw caught\n\t\treturn refresh()\n\t}\n}\n\n/**\n * A 64-bit FNV-1a digest of an API key: the same for the same key, different for another in\n * practice, and too short to recover the key from.\n */\nfunction keyDigest(apiKey: string): string {\n\tlet hash = 0xcbf29ce484222325n\n\tfor (const byte of new TextEncoder().encode(apiKey)) {\n\t\thash = ((hash ^ BigInt(byte)) * 0x100000001b3n) & 0xffffffffffffffffn\n\t}\n\treturn hash.toString(36)\n}\n\n/**\n * The credential a client holds, and everything that keeps it valid. Each\n * `createRasterClient` has its own, so clients on one page, such as one per Sanity Studio\n * workspace, never share a token.\n */\nexport interface SessionStore {\n\t/** The credentials in memory. `undefined` until `hydrate()` has run. */\n\tcurrent(): StoredCredentials | undefined\n\t/** Load from the `CredentialStore`. Idempotent; safe to await more than once. */\n\thydrate(): Promise<StoredCredentials>\n\t/** Persist, then replace in memory. A failed write changes nothing and rejects with its error. */\n\tsave(credentials: StoredCredentials): Promise<void>\n\t/** Called on every change — a sign-in, a token refresh, a sign-out. */\n\tsubscribe(listener: (credentials: StoredCredentials) => void): () => void\n\tisSignedIn(): boolean\n\t/** Whether there is any credential at all (a session or an API key). */\n\tisConfigured(): boolean\n\tcredentialIdentity(): string | null\n\tgetAccessToken(options?: { rejected?: string }): Promise<string>\n\tsignOut(): Promise<void>\n}\n\nexport function createSessionStore(options: {\n\tcredentials: CredentialStore\n\tauth: AuthContext\n}): SessionStore {\n\tconst { credentials: store, auth } = options\n\n\tlet current: StoredCredentials | undefined\n\t/** What `save` is writing, which memory takes only once the store has it. */\n\tlet writing: StoredCredentials | undefined\n\tlet hydrating: Promise<StoredCredentials> | null = null\n\tlet refreshing: Promise<string> | null = null\n\tconst listeners = new Set<(credentials: StoredCredentials) => void>()\n\n\tfunction emit(next: StoredCredentials): void {\n\t\tcurrent = next\n\t\tfor (const listener of listeners) listener(next)\n\t}\n\n\t/**\n\t * Write first, then change memory and tell listeners. A failed write leaves memory as it\n\t * was and rejects with the store's own error, so a sign-in or sign-out the store never took\n\t * is not in use either.\n\t */\n\tasync function save(next: StoredCredentials): Promise<void> {\n\t\twriting = next\n\t\ttry {\n\t\t\tawait store.save(next)\n\t\t} finally {\n\t\t\tif (writing === next) writing = undefined\n\t\t}\n\t\temit(next)\n\t}\n\n\t/**\n\t * Read the store, filling in the fields a credential saved before they existed lacks:\n\t * a missing `oauth` is not `null`, so it would read as signed in.\n\t */\n\tasync function load(): Promise<StoredCredentials | null> {\n\t\tconst stored = await store.load()\n\t\treturn stored === null ? null : { ...emptyCredentials(), ...stored }\n\t}\n\n\t/** Signed-out credentials that keep this install's registration (see `clientId`). */\n\tfunction signedOut(): StoredCredentials {\n\t\treturn { ...SIGNED_OUT, clientId: current?.clientId ?? null }\n\t}\n\n\t/** Whether the stored session, or the one being written, is still the one a refresh started from. */\n\tfunction isSameSession(session: OAuthSession): boolean {\n\t\treturn (writing ?? current)?.oauth?.refreshToken === session.refreshToken\n\t}\n\n\t/**\n\t * Single-flight: a provider and a first request can both call this on mount, and two\n\t * concurrent loads would race to `emit` — the later one winning even if it read staler\n\t * data.\n\t */\n\tfunction hydrate(): Promise<StoredCredentials> {\n\t\thydrating ??= load()\n\t\t\t.then((loaded) => {\n\t\t\t\tconst next = loaded ?? emptyCredentials()\n\t\t\t\temit(next)\n\t\t\t\treturn next\n\t\t\t})\n\t\t\t.catch((caught) => {\n\t\t\t\t// Clear the cached promise so a transient read failure can be retried rather\n\t\t\t\t// than poisoning every later call.\n\t\t\t\thydrating = null\n\t\t\t\tthrow caught\n\t\t\t})\n\t\treturn hydrating\n\t}\n\n\tasync function refresh(session: OAuthSession): Promise<OAuthSession> {\n\t\tlet next: OAuthSession\n\t\ttry {\n\t\t\tnext = await refreshSession(auth, session)\n\t\t} catch (caught) {\n\t\t\t// The connection is gone — revoked under Connected apps, membership lost, or the\n\t\t\t// token was spent already. Only signing in again fixes that, so drop the dead\n\t\t\t// session now rather than fail every request with it.\n\t\t\tif (caught instanceof RasterApiError && caught.code === 'invalid_grant') {\n\t\t\t\tif (isSameSession(session)) await save(signedOut())\n\t\t\t\tthrow new RasterApiError(\n\t\t\t\t\t'Your Raster session has ended. Sign in again.',\n\t\t\t\t\t'SESSION_EXPIRED',\n\t\t\t\t\t401\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow caught\n\t\t}\n\n\t\t// The old refresh token died the moment this one was minted, so memory takes the new\n\t\t// one first and keeps it even if the write fails; the token is handed out only once\n\t\t// written. Skipped if the session changed under us (signed out, or signed in again)\n\t\t// while the refresh was in flight — that newer session must not be clobbered.\n\t\tif (current !== undefined && isSameSession(session)) {\n\t\t\tconst rotated = { ...current, oauth: next }\n\t\t\temit(rotated)\n\t\t\tawait store.save(rotated)\n\t\t}\n\t\treturn next\n\t}\n\n\t/**\n\t * The bearer the credentials can send as they stand, or the session to refresh first:\n\t * its token is about to expire, or is the `rejected` one a request just got a 401 with.\n\t */\n\tfunction tokenOrStale(\n\t\tcredentials: StoredCredentials | undefined,\n\t\trejected: string | undefined\n\t): string | OAuthSession {\n\t\tif (credentials === undefined || credentials.oauth === null) {\n\t\t\tconst apiKey = credentials?.apiKey\n\t\t\tif (!apiKey) throw new RasterApiError('Sign in to Raster first.', 'NOT_SIGNED_IN', 401)\n\t\t\treturn apiKey\n\t\t}\n\n\t\tconst { oauth } = credentials\n\t\tconst fresh = Date.now() < oauth.expiresAt - EXPIRY_MARGIN_MS\n\t\t// A rejected token that has already been replaced here: another request refreshed\n\t\t// first, so this one can simply use the new token.\n\t\treturn fresh && oauth.accessToken !== rejected ? oauth.accessToken : oauth\n\t}\n\n\t/**\n\t * Refresh unless another tab sharing the store got there first. Its copy wins — it may\n\t * have rotated the token, signed out, or signed in as somebody else — unless this tab\n\t * changed its own credentials while waiting. A store that reads back null is unreadable\n\t * (blocked storage), not signed out.\n\t */\n\tasync function refreshLatest(\n\t\tfrom: StoredCredentials | undefined,\n\t\trejected: string | undefined\n\t): Promise<string> {\n\t\tconst stored = await load()\n\t\tif (\n\t\t\tstored !== null &&\n\t\t\tcurrent === from &&\n\t\t\tstored.oauth?.refreshToken !== from?.oauth?.refreshToken\n\t\t) {\n\t\t\temit(stored)\n\t\t}\n\t\tconst found = tokenOrStale(current, rejected)\n\t\treturn typeof found === 'string' ? found : (await refresh(found)).accessToken\n\t}\n\n\treturn {\n\t\tcurrent() {\n\t\t\treturn current\n\t\t},\n\n\t\thydrate,\n\n\t\tsave,\n\n\t\tsubscribe(listener) {\n\t\t\tlisteners.add(listener)\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener)\n\t\t\t}\n\t\t},\n\n\t\tisSignedIn() {\n\t\t\treturn current !== undefined && current.oauth !== null\n\t\t},\n\n\t\tisConfigured() {\n\t\t\treturn (\n\t\t\t\tcurrent !== undefined &&\n\t\t\t\t(current.oauth !== null || (typeof current.apiKey === 'string' && current.apiKey !== ''))\n\t\t\t)\n\t\t},\n\n\t\t/**\n\t\t * Identifies WHOSE credential is in use, so a caller can tell a token refresh apart\n\t\t * from a different account signing in. Stable across refreshes and reloads, and new\n\t\t * with every sign-in, even one through the same client (see `OAuthSession.signInId`).\n\t\t * A session saved before sign-ins had an id falls back to its client. An API key is\n\t\t * named by its digest, so the key itself never lands in a cache key or a log.\n\t\t */\n\t\tcredentialIdentity() {\n\t\t\tif (current === undefined) return null\n\t\t\tconst { oauth, apiKey } = current\n\t\t\tif (oauth !== null) return `oauth:${oauth.signInId ?? oauth.clientId}`\n\t\t\treturn apiKey === null ? null : `key:${keyDigest(apiKey)}`\n\t\t},\n\n\t\t/**\n\t\t * The bearer to send: the API key, or the session's access token, refreshed first when\n\t\t * it is about to expire or is the `rejected` one. Refreshes are single-flight, because\n\t\t * the server treats a second use of a rotated refresh token as theft and revokes the\n\t\t * whole connection; tabs sharing a store share one too (`refreshLatest`).\n\t\t */\n\t\tasync getAccessToken(tokenOptions = {}) {\n\t\t\tif (current === undefined) await hydrate()\n\n\t\t\tconst found = tokenOrStale(current, tokenOptions.rejected)\n\t\t\tif (typeof found === 'string') return found\n\n\t\t\tconst from = current\n\t\t\trefreshing ??= withRefreshLock(() => refreshLatest(from, tokenOptions.rejected)).finally(\n\t\t\t\t() => {\n\t\t\t\t\trefreshing = null\n\t\t\t\t}\n\t\t\t)\n\t\t\treturn refreshing\n\t\t},\n\n\t\t/**\n\t\t * Sign out: clear the session, and revoke it in Raster (best-effort — it is gone\n\t\t * locally either way, and a failed revoke must not leave the user stuck signed in).\n\t\t */\n\t\tasync signOut() {\n\t\t\tconst oauth = current?.oauth ?? null\n\t\t\tawait save(signedOut())\n\t\t\tif (oauth !== null) await revokeSession(auth, oauth).catch(() => {})\n\t\t},\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,13 +1,20 @@
1
1
  {
2
2
  "name": "@raster-app/sdk",
3
- "version": "0.1.0-canary-fd0f8dd",
3
+ "version": "0.1.0-rc.0",
4
4
  "description": "Framework-free client for the Raster REST API: OAuth, sessions, assets, libraries, search and image helpers.",
5
- "license": "MIT",
6
- "homepage": "https://raster.app/docs",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/raster-app/raster-sdk.git",
9
+ "directory": "packages/sdk"
10
+ },
11
+ "homepage": "https://github.com/raster-app/raster-sdk/tree/main/packages/sdk#readme",
7
12
  "keywords": [
8
13
  "raster",
9
14
  "dam",
10
15
  "assets",
16
+ "figma",
17
+ "sanity",
11
18
  "plugin"
12
19
  ],
13
20
  "type": "module",
@@ -28,7 +35,6 @@
28
35
  },
29
36
  "scripts": {
30
37
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
31
- "prepack": "bun run build",
32
38
  "dev": "tsc -p tsconfig.build.json --watch",
33
39
  "check-types": "tsc --noEmit",
34
40
  "lint": "biome lint --error-on-warnings .",
@@ -37,4 +43,4 @@
37
43
  "publishConfig": {
38
44
  "access": "public"
39
45
  }
40
- }
46
+ }