@immediately-run/sdk 0.35.0 → 0.37.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/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/ipc.cjs +10 -0
- package/dist/ipc.cjs.map +1 -1
- package/dist/ipc.d.cts +30 -1
- package/dist/ipc.d.ts +30 -1
- package/dist/ipc.js +9 -0
- package/dist/ipc.js.map +1 -1
- package/dist/mounts.cjs +28 -4
- package/dist/mounts.cjs.map +1 -1
- package/dist/mounts.d.cts +29 -4
- package/dist/mounts.d.ts +29 -4
- package/dist/mounts.js +27 -4
- package/dist/mounts.js.map +1 -1
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -12,10 +12,10 @@ export { EditorContext, getEditorContext, onEditorContextChange, useEditorContex
|
|
|
12
12
|
export { EditTarget, EditorOpenError, EditorSessionError, EditorWriteError, RequestEditError, closeFile, createFile, createFolder, deleteEntry, openInEditor, renameEntry, requestEdit, setActiveFile, uploadFile } from './editor.cjs';
|
|
13
13
|
export { FormFactor, FormFactorClass, Orientation, getFormFactor, onFormFactorChange, useFormFactor } from './formFactor.cjs';
|
|
14
14
|
export { getRegion, useRegion } from './region.cjs';
|
|
15
|
-
export { GrantRecord, Invite, Member, MountQuery, MountRemoveReason, MountRule, RemovedMount, ResolvedUser, Role, SandboxMount, SessionMount, SpaceError, SpaceInfo, acceptInvite, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount } from './mounts.cjs';
|
|
15
|
+
export { GrantRecord, Invite, Member, MountQuery, MountRemoveReason, MountRule, RemovedMount, ResolvedUser, Role, SandboxMount, SessionMount, SpaceError, SpaceInfo, acceptInvite, awaitMatchingMount, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount } from './mounts.cjs';
|
|
16
16
|
export { ContributeMode, ContributeOptions, ContributionEvent, ContributionResult, contribute } from './contribute.cjs';
|
|
17
17
|
export { ApiMethod, getCatalog, invoke, invokeStream, onCatalogChange, useCatalog } from './catalog.cjs';
|
|
18
|
-
export { RegionMessage, onRegionMessage, postToRegion, useRegionMessage } from './ipc.cjs';
|
|
18
|
+
export { RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage } from './ipc.cjs';
|
|
19
19
|
export { DraggableItem, DroppedItem, ItemDragError, cancelItemDrag, onItemDrop, startItemDrag, useDroppedItem } from './dnd.cjs';
|
|
20
20
|
export { HostFetchInit, HostFetchResponse, HostFetchStreamEvent, HostFetchStreamResult, hostFetch, hostFetchStream } from './netFetch.cjs';
|
|
21
21
|
export { SecretError, SecretGrant, SecretHints, SecretQuery, SecretType, SecretView, getSecrets, onSecretsChange, requestAddSecret, requestSecret, revokeSecret, useSecrets } from './secrets.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -12,10 +12,10 @@ export { EditorContext, getEditorContext, onEditorContextChange, useEditorContex
|
|
|
12
12
|
export { EditTarget, EditorOpenError, EditorSessionError, EditorWriteError, RequestEditError, closeFile, createFile, createFolder, deleteEntry, openInEditor, renameEntry, requestEdit, setActiveFile, uploadFile } from './editor.js';
|
|
13
13
|
export { FormFactor, FormFactorClass, Orientation, getFormFactor, onFormFactorChange, useFormFactor } from './formFactor.js';
|
|
14
14
|
export { getRegion, useRegion } from './region.js';
|
|
15
|
-
export { GrantRecord, Invite, Member, MountQuery, MountRemoveReason, MountRule, RemovedMount, ResolvedUser, Role, SandboxMount, SessionMount, SpaceError, SpaceInfo, acceptInvite, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount } from './mounts.js';
|
|
15
|
+
export { GrantRecord, Invite, Member, MountQuery, MountRemoveReason, MountRule, RemovedMount, ResolvedUser, Role, SandboxMount, SessionMount, SpaceError, SpaceInfo, acceptInvite, awaitMatchingMount, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount } from './mounts.js';
|
|
16
16
|
export { ContributeMode, ContributeOptions, ContributionEvent, ContributionResult, contribute } from './contribute.js';
|
|
17
17
|
export { ApiMethod, getCatalog, invoke, invokeStream, onCatalogChange, useCatalog } from './catalog.js';
|
|
18
|
-
export { RegionMessage, onRegionMessage, postToRegion, useRegionMessage } from './ipc.js';
|
|
18
|
+
export { RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage } from './ipc.js';
|
|
19
19
|
export { DraggableItem, DroppedItem, ItemDragError, cancelItemDrag, onItemDrop, startItemDrag, useDroppedItem } from './dnd.js';
|
|
20
20
|
export { HostFetchInit, HostFetchResponse, HostFetchStreamEvent, HostFetchStreamResult, hostFetch, hostFetchStream } from './netFetch.js';
|
|
21
21
|
export { SecretError, SecretGrant, SecretHints, SecretQuery, SecretType, SecretView, getSecrets, onSecretsChange, requestAddSecret, requestSecret, revokeSecret, useSecrets } from './secrets.js';
|
package/dist/ipc.cjs
CHANGED
|
@@ -20,6 +20,7 @@ var ipc_exports = {};
|
|
|
20
20
|
__export(ipc_exports, {
|
|
21
21
|
onRegionMessage: () => onRegionMessage,
|
|
22
22
|
postToRegion: () => postToRegion,
|
|
23
|
+
revealRegion: () => revealRegion,
|
|
23
24
|
useRegionMessage: () => useRegionMessage
|
|
24
25
|
});
|
|
25
26
|
module.exports = __toCommonJS(ipc_exports);
|
|
@@ -33,6 +34,14 @@ const postToRegion = async (region, data) => {
|
|
|
33
34
|
throw err;
|
|
34
35
|
}
|
|
35
36
|
};
|
|
37
|
+
const revealRegion = async (region) => {
|
|
38
|
+
const res = await (0, import_sandboxUtils.protocolRequest)("ipc", "reveal", [{ to: region }]);
|
|
39
|
+
if (!res || res.ok !== true) {
|
|
40
|
+
const err = new Error(res?.message ?? "ipc reveal failed");
|
|
41
|
+
err.code = res?.code ?? "unknown";
|
|
42
|
+
throw err;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
36
45
|
const onRegionMessage = (listener) => (0, import_sandboxUtils.addListener)(
|
|
37
46
|
"region-message",
|
|
38
47
|
(m) => listener({ from: m.from, data: m.data })
|
|
@@ -46,6 +55,7 @@ const useRegionMessage = () => {
|
|
|
46
55
|
0 && (module.exports = {
|
|
47
56
|
onRegionMessage,
|
|
48
57
|
postToRegion,
|
|
58
|
+
revealRegion,
|
|
49
59
|
useRegionMessage
|
|
50
60
|
});
|
|
51
61
|
//# sourceMappingURL=ipc.cjs.map
|
package/dist/ipc.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAoC;AACpC,0BAA6C;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,UAAM,qCAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,iBAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,QAAI,uBAA+B,IAAI;AACzD,8BAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Ask the host to bring the user to `region` — the `reveal`-class method of\n * UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column\n * transition (the panel's carousel advances to the main pane); on desktop a focus\n * move. Use it when a tap in your panel produces something to look at in another\n * column, right after the `postToRegion` that sends it there:\n *\n * ```ts\n * onClick={() => { // a REAL user gesture\n * void postToRegion('stage.conversation', { type: 'select-conversation', id });\n * void revealRegion('stage.conversation');\n * }}\n * ```\n *\n * **Call it synchronously inside a user-gesture handler.** The host reads its own\n * transient user activation and refuses without one — an app flipping columns on a\n * timer is the attention-steal primitive §4.1 is written against. It reaches only\n * regions you already have a two-sided IPC edge to, and only within the active\n * activity, so it can neither jump the user into an unrelated surface nor pull\n * focus back to the caller's own column.\n *\n * Resolves once the host has *considered* the request — deliberately NOT reporting\n * whether focus actually moved. Whether the user is moved is the host's call\n * (activation, rate limit, already-there), and an app that could observe the\n * refusal would be tempted to retry, which is the behaviour the gate exists to\n * stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`\n * capability, or no declared edge to `region`.\n */\nexport const revealRegion = async (region: string): Promise<void> => {\n const res = (await protocolRequest('ipc', 'reveal', [{ to: region }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc reveal failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAoC;AACpC,0BAA6C;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,UAAM,qCAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AA8BO,MAAM,eAAe,OAAO,WAAkC;AACnE,QAAM,MAAO,UAAM,qCAAgB,OAAO,UAAU,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC;AAIpE,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,mBAAmB;AACzD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,iBAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,QAAI,uBAA+B,IAAI;AACzD,8BAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
|
package/dist/ipc.d.cts
CHANGED
|
@@ -10,9 +10,38 @@ interface RegionMessage {
|
|
|
10
10
|
* lacks the `ipc` capability.
|
|
11
11
|
*/
|
|
12
12
|
declare const postToRegion: (region: string, data: unknown) => Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Ask the host to bring the user to `region` — the `reveal`-class method of
|
|
15
|
+
* UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column
|
|
16
|
+
* transition (the panel's carousel advances to the main pane); on desktop a focus
|
|
17
|
+
* move. Use it when a tap in your panel produces something to look at in another
|
|
18
|
+
* column, right after the `postToRegion` that sends it there:
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* onClick={() => { // a REAL user gesture
|
|
22
|
+
* void postToRegion('stage.conversation', { type: 'select-conversation', id });
|
|
23
|
+
* void revealRegion('stage.conversation');
|
|
24
|
+
* }}
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* **Call it synchronously inside a user-gesture handler.** The host reads its own
|
|
28
|
+
* transient user activation and refuses without one — an app flipping columns on a
|
|
29
|
+
* timer is the attention-steal primitive §4.1 is written against. It reaches only
|
|
30
|
+
* regions you already have a two-sided IPC edge to, and only within the active
|
|
31
|
+
* activity, so it can neither jump the user into an unrelated surface nor pull
|
|
32
|
+
* focus back to the caller's own column.
|
|
33
|
+
*
|
|
34
|
+
* Resolves once the host has *considered* the request — deliberately NOT reporting
|
|
35
|
+
* whether focus actually moved. Whether the user is moved is the host's call
|
|
36
|
+
* (activation, rate limit, already-there), and an app that could observe the
|
|
37
|
+
* refusal would be tempted to retry, which is the behaviour the gate exists to
|
|
38
|
+
* stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`
|
|
39
|
+
* capability, or no declared edge to `region`.
|
|
40
|
+
*/
|
|
41
|
+
declare const revealRegion: (region: string) => Promise<void>;
|
|
13
42
|
/** Subscribe to inbound region messages. Returns an unsubscribe fn. */
|
|
14
43
|
declare const onRegionMessage: (listener: (msg: RegionMessage) => void) => (() => void);
|
|
15
44
|
/** React hook: the most recent inbound region message (or `null`). */
|
|
16
45
|
declare const useRegionMessage: () => RegionMessage | null;
|
|
17
46
|
|
|
18
|
-
export { type RegionMessage, onRegionMessage, postToRegion, useRegionMessage };
|
|
47
|
+
export { type RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage };
|
package/dist/ipc.d.ts
CHANGED
|
@@ -10,9 +10,38 @@ interface RegionMessage {
|
|
|
10
10
|
* lacks the `ipc` capability.
|
|
11
11
|
*/
|
|
12
12
|
declare const postToRegion: (region: string, data: unknown) => Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Ask the host to bring the user to `region` — the `reveal`-class method of
|
|
15
|
+
* UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column
|
|
16
|
+
* transition (the panel's carousel advances to the main pane); on desktop a focus
|
|
17
|
+
* move. Use it when a tap in your panel produces something to look at in another
|
|
18
|
+
* column, right after the `postToRegion` that sends it there:
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* onClick={() => { // a REAL user gesture
|
|
22
|
+
* void postToRegion('stage.conversation', { type: 'select-conversation', id });
|
|
23
|
+
* void revealRegion('stage.conversation');
|
|
24
|
+
* }}
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* **Call it synchronously inside a user-gesture handler.** The host reads its own
|
|
28
|
+
* transient user activation and refuses without one — an app flipping columns on a
|
|
29
|
+
* timer is the attention-steal primitive §4.1 is written against. It reaches only
|
|
30
|
+
* regions you already have a two-sided IPC edge to, and only within the active
|
|
31
|
+
* activity, so it can neither jump the user into an unrelated surface nor pull
|
|
32
|
+
* focus back to the caller's own column.
|
|
33
|
+
*
|
|
34
|
+
* Resolves once the host has *considered* the request — deliberately NOT reporting
|
|
35
|
+
* whether focus actually moved. Whether the user is moved is the host's call
|
|
36
|
+
* (activation, rate limit, already-there), and an app that could observe the
|
|
37
|
+
* refusal would be tempted to retry, which is the behaviour the gate exists to
|
|
38
|
+
* stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`
|
|
39
|
+
* capability, or no declared edge to `region`.
|
|
40
|
+
*/
|
|
41
|
+
declare const revealRegion: (region: string) => Promise<void>;
|
|
13
42
|
/** Subscribe to inbound region messages. Returns an unsubscribe fn. */
|
|
14
43
|
declare const onRegionMessage: (listener: (msg: RegionMessage) => void) => (() => void);
|
|
15
44
|
/** React hook: the most recent inbound region message (or `null`). */
|
|
16
45
|
declare const useRegionMessage: () => RegionMessage | null;
|
|
17
46
|
|
|
18
|
-
export { type RegionMessage, onRegionMessage, postToRegion, useRegionMessage };
|
|
47
|
+
export { type RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage };
|
package/dist/ipc.js
CHANGED
|
@@ -9,6 +9,14 @@ const postToRegion = async (region, data) => {
|
|
|
9
9
|
throw err;
|
|
10
10
|
}
|
|
11
11
|
};
|
|
12
|
+
const revealRegion = async (region) => {
|
|
13
|
+
const res = await protocolRequest("ipc", "reveal", [{ to: region }]);
|
|
14
|
+
if (!res || res.ok !== true) {
|
|
15
|
+
const err = new Error(res?.message ?? "ipc reveal failed");
|
|
16
|
+
err.code = res?.code ?? "unknown";
|
|
17
|
+
throw err;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
12
20
|
const onRegionMessage = (listener) => addListener(
|
|
13
21
|
"region-message",
|
|
14
22
|
(m) => listener({ from: m.from, data: m.data })
|
|
@@ -21,6 +29,7 @@ const useRegionMessage = () => {
|
|
|
21
29
|
export {
|
|
22
30
|
onRegionMessage,
|
|
23
31
|
postToRegion,
|
|
32
|
+
revealRegion,
|
|
24
33
|
useRegionMessage
|
|
25
34
|
};
|
|
26
35
|
//# sourceMappingURL=ipc.js.map
|
package/dist/ipc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";AAIA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,mBAAmB;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,MAAM,gBAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,aAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,IAAI,SAA+B,IAAI;AACzD,YAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Ask the host to bring the user to `region` — the `reveal`-class method of\n * UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column\n * transition (the panel's carousel advances to the main pane); on desktop a focus\n * move. Use it when a tap in your panel produces something to look at in another\n * column, right after the `postToRegion` that sends it there:\n *\n * ```ts\n * onClick={() => { // a REAL user gesture\n * void postToRegion('stage.conversation', { type: 'select-conversation', id });\n * void revealRegion('stage.conversation');\n * }}\n * ```\n *\n * **Call it synchronously inside a user-gesture handler.** The host reads its own\n * transient user activation and refuses without one — an app flipping columns on a\n * timer is the attention-steal primitive §4.1 is written against. It reaches only\n * regions you already have a two-sided IPC edge to, and only within the active\n * activity, so it can neither jump the user into an unrelated surface nor pull\n * focus back to the caller's own column.\n *\n * Resolves once the host has *considered* the request — deliberately NOT reporting\n * whether focus actually moved. Whether the user is moved is the host's call\n * (activation, rate limit, already-there), and an app that could observe the\n * refusal would be tempted to retry, which is the behaviour the gate exists to\n * stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`\n * capability, or no declared edge to `region`.\n */\nexport const revealRegion = async (region: string): Promise<void> => {\n const res = (await protocolRequest('ipc', 'reveal', [{ to: region }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc reveal failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";AAIA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,mBAAmB;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,MAAM,gBAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AA8BO,MAAM,eAAe,OAAO,WAAkC;AACnE,QAAM,MAAO,MAAM,gBAAgB,OAAO,UAAU,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC;AAIpE,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,mBAAmB;AACzD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,aAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,IAAI,SAA+B,IAAI;AACzD,YAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
|
package/dist/mounts.cjs
CHANGED
|
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
19
19
|
var mounts_exports = {};
|
|
20
20
|
__export(mounts_exports, {
|
|
21
21
|
acceptInvite: () => acceptInvite,
|
|
22
|
+
awaitMatchingMount: () => awaitMatchingMount,
|
|
22
23
|
createSpace: () => createSpace,
|
|
23
24
|
declineInvite: () => declineInvite,
|
|
24
25
|
findMount: () => findMount,
|
|
@@ -128,14 +129,35 @@ const onMountsChange = (listener) => {
|
|
|
128
129
|
const disposable = mountService().onChange(listener);
|
|
129
130
|
return () => disposable.dispose();
|
|
130
131
|
};
|
|
131
|
-
const waitForMount = (query) =>
|
|
132
|
-
|
|
132
|
+
const waitForMount = (query, timeoutMs) => awaitMatchingMount(onMountsChange, query, timeoutMs);
|
|
133
|
+
const awaitMatchingMount = (subscribe, query, timeoutMs) => new Promise((resolve, reject) => {
|
|
134
|
+
let unsubscribe;
|
|
135
|
+
let settled = false;
|
|
136
|
+
let timer;
|
|
137
|
+
const stop = () => {
|
|
138
|
+
settled = true;
|
|
139
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
140
|
+
void Promise.resolve().then(() => unsubscribe?.());
|
|
141
|
+
};
|
|
142
|
+
unsubscribe = subscribe((mounts) => {
|
|
143
|
+
if (settled) return;
|
|
133
144
|
const found = mounts.find((m) => matches(m, query));
|
|
134
145
|
if (found) {
|
|
135
|
-
|
|
146
|
+
stop();
|
|
136
147
|
resolve(found);
|
|
137
148
|
}
|
|
138
149
|
});
|
|
150
|
+
if (!settled && timeoutMs !== void 0) {
|
|
151
|
+
timer = setTimeout(() => {
|
|
152
|
+
if (settled) return;
|
|
153
|
+
stop();
|
|
154
|
+
const err = new Error(
|
|
155
|
+
`waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`
|
|
156
|
+
);
|
|
157
|
+
err.code = "timeout";
|
|
158
|
+
reject(err);
|
|
159
|
+
}, timeoutMs);
|
|
160
|
+
}
|
|
139
161
|
});
|
|
140
162
|
const useMounts = () => {
|
|
141
163
|
const [mounts, setMounts] = (0, import_react.useState)(getMounts);
|
|
@@ -188,8 +210,9 @@ const settingsRequest = async (method, query = {}) => {
|
|
|
188
210
|
};
|
|
189
211
|
const openSettings = async () => {
|
|
190
212
|
const mount2 = await settingsRequest("open");
|
|
191
|
-
return waitForMount({ id: mount2.id ?? mount2.path });
|
|
213
|
+
return waitForMount({ id: mount2.id ?? mount2.path }, SETTINGS_MOUNT_TIMEOUT_MS);
|
|
192
214
|
};
|
|
215
|
+
const SETTINGS_MOUNT_TIMEOUT_MS = 15e3;
|
|
193
216
|
const importSettingsFromParent = async () => {
|
|
194
217
|
try {
|
|
195
218
|
const data = await settingsRequest("importFromParent");
|
|
@@ -247,6 +270,7 @@ const revokeGrant = async (appKey, spaceId) => {
|
|
|
247
270
|
// Annotate the CommonJS export names for ESM import in node:
|
|
248
271
|
0 && (module.exports = {
|
|
249
272
|
acceptInvite,
|
|
273
|
+
awaitMatchingMount,
|
|
250
274
|
createSpace,
|
|
251
275
|
declineInvite,
|
|
252
276
|
findMount,
|
package/dist/mounts.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? '/app';\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: \"ro\" | \"rw\";\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason =\n | \"revoked\"\n | \"unshared\"\n | \"signed-out\"\n | \"unmounted\"\n | \"deleted\";\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n ): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value)\n ? (value as MountRemoveReason)\n : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener('mount-add', (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener('mount-remove', (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage('request-mounts');\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean =>\n mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined =>\n getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n */\nexport const waitForMount = (query: MountQuery): Promise<SandboxMount> =>\n new Promise((resolve) => {\n const unsubscribe = onMountsChange((mounts) => {\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n // Defer unsubscribe so we don't dispose during the initial replay call.\n Promise.resolve().then(unsubscribe);\n resolve(found);\n }\n });\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: 'session-mounts',\n requestType: 'request-session-mounts',\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (\n listener: (mounts: SessionMount[]) => void,\n): (() => void) => sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** Summary of a space, as returned by {@link listSpaces}. */\nexport interface SpaceInfo {\n spaceId: string;\n role?: 'owner' | 'writer' | 'reader';\n owner?: string;\n name?: string;\n}\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n | 'unknown';\n}\n\ntype SpaceResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('spaces', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (\n method: string,\n query: Record<string, unknown>,\n): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> =>\n requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> =>\n mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> =>\n requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n */\nexport const makeContentRef = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('settings', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> =>\n settingsRequest<string[]>('list');\n\n/** Create a brand-new, empty platform-hosted space. The app reaches it (or any\n * other space) afterward through the {@link requestMount} powerbox or\n * {@link mountSpace}; there is no implicit per-app binding. */\nexport const createSpace = (\n opts: { name?: string } = {}\n): Promise<SandboxMount> => requestMountInternal('create', opts);\n\n/** List spaces you can access — all of them, or just those bound to this app. */\nexport const listSpaces = (opts: { app?: boolean } = {}): Promise<SpaceInfo[]> =>\n request<SpaceInfo[]>('list', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A collaborator's role on a shared space: full `owner`, read-write `writer`, or read-only `reader`. */\nexport type Role = 'owner' | 'writer' | 'reader';\n\n/** A member of a space (for the share/manage UI). */\nexport interface Member {\n /**\n * The **grantee** — `user:{uid}` | `group:{gid}`. This is the canonical name\n * (core_concepts §4: \"principal\" is reserved for the authority context; a space\n * member is a *grantee*). The host populates this on every member row.\n */\n grantee: string;\n /**\n * @deprecated Use {@link Member.grantee}. Kept as an alias (same value) for\n * back-compat during the `principal`→`grantee` migration; will be removed in a\n * future major. The host still populates both.\n */\n principal: string;\n role: Role;\n login?: string;\n avatarUrl?: string;\n}\n\n/** A handle resolved to a principal (handle → who). */\nexport interface ResolvedUser {\n uid: string;\n login: string;\n avatarUrl?: string;\n}\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** Enumerate ALL the user's spaces (not just this app's) — `spaces:user`. */\nexport const listAllSpaces = (): Promise<SpaceInfo[]> => request<SpaceInfo[]>('listAll', {});\n\n/** Read a space's members one-shot — `spaces:admin`. */\nexport const getSpaceMembers = (spaceId: string): Promise<Member[]> =>\n request<Member[]>('members', { spaceId });\n\n/** Invite a user (by provider handle) to a space at a role — `spaces:admin`. The\n * host resolves the handle, so the app never sees other users' uids except the one\n * it invited. Pull-based (FILE_SHARING_SPEC §6.4): this writes an INVITATION, not\n * membership — the recipient must {@link acceptInvite}. Re-inviting an already-\n * invited/member user is idempotent. */\nexport const inviteToSpace = async (spaceId: string, login: string, role: Role): Promise<void> => {\n await request('invite', { spaceId, login, role });\n};\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: 'invitations',\n requestType: 'request-invitations',\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n/** Remove a member from a space — `spaces:admin`. Refused if it would orphan the\n * space (owner-lockout, T41). */\nexport const unshareSpace = async (spaceId: string, uid: string): Promise<void> => {\n await request('unshare', { spaceId, uid });\n};\n\n/** Change a member's role — `spaces:admin`. Refused if it would drop the sole\n * owner (owner-lockout, T41). */\nexport const setSpaceRole = async (spaceId: string, uid: string, role: Role): Promise<void> => {\n await request('setRole', { spaceId, uid, role });\n};\n\n/** Resolve a provider handle to a principal (for the invite flow) — `spaces:admin`,\n * rate-limited host-side. */\nexport const lookupUser = (login: string): Promise<ResolvedUser> =>\n request<ResolvedUser>('lookupUser', { login });\n\n/** One durable grant an app holds, for the §8.11 capability audit view. */\nexport interface GrantRecord {\n /** The app's provider-qualified identity (`provider__namespace__repository`). */\n appKey: string;\n spaceId: string;\n /** Universal mount id (§3.5). */\n mountId: string;\n subtree?: string;\n mode: 'ro' | 'rw';\n name?: string;\n}\n\n/** Enumerate every (app, mount) grant the user holds — the audit view\n * (§8.11). Elevated `spaces:admin`. */\nexport const listGrants = (): Promise<GrantRecord[]> => request<GrantRecord[]>('grants', {});\n\n/** Revoke one app's grant on a space — durable (the app can't re-mount) plus a\n * best-effort live teardown. Elevated `spaces:admin`. */\nexport const revokeGrant = async (appKey: string, spaceId: string): Promise<void> => {\n await request('revokeGrant', { appKey, spaceId });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AAC,CAAC;AAIpF,MAAM,cAAc,OAAO,QAAgB,YAAmC;AACnF,QAAM,QAAQ,eAAe,EAAE,QAAQ,QAAQ,CAAC;AAClD;","names":["mount"]}
|
|
1
|
+
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? '/app';\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: \"ro\" | \"rw\";\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason =\n | \"revoked\"\n | \"unshared\"\n | \"signed-out\"\n | \"unmounted\"\n | \"deleted\";\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n ): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value)\n ? (value as MountRemoveReason)\n : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener('mount-add', (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener('mount-remove', (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage('request-mounts');\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean =>\n mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined =>\n getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n *\n * `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of\n * waiting forever. Omit it to keep the original unbounded behaviour — but prefer\n * setting it on any path whose caller would otherwise hang silently: a mount that\n * never arrives is indistinguishable from one that is merely slow, and an awaited\n * promise that never settles surfaces to the user as a feature that quietly does\n * nothing.\n *\n * **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the\n * documented initial replay). So when the mount is already present — the common\n * case, since callers typically `await` the host request that creates it first —\n * the callback below runs *during* the `onMountsChange(...)` call, before the\n * assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with\n * `let` ABOVE the subscription and read only inside a deferred closure: writing\n * `const unsubscribe = onMountsChange(...)` and referencing it in the callback\n * throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a\n * temporal-dead-zone read) on exactly that path. That bug silently broke\n * `openSettings()` — and with it the agent's conversation memory.\n */\nexport const waitForMount = (\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> => awaitMatchingMount(onMountsChange, query, timeoutMs);\n\n/** The framework-free core of {@link waitForMount}, with the subscription injected\n * so a test can drive the synchronous-initial-replay case that broke it. */\nexport const awaitMatchingMount = (\n subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void,\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> =>\n new Promise((resolve, reject) => {\n // `let`, declared BEFORE `subscribe(...)` — see the hazard note above. A\n // `const` bound to the subscribe call is in its temporal dead zone while the\n // synchronous initial replay runs, and any read of it from the listener\n // throws.\n let unsubscribe: (() => void) | undefined;\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // Deferred so we never dispose the subscription from inside its own initial\n // replay, and late enough that `unsubscribe` is always assigned.\n const stop = (): void => {\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n void Promise.resolve().then(() => unsubscribe?.());\n };\n unsubscribe = subscribe((mounts) => {\n if (settled) return;\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n stop();\n resolve(found);\n }\n });\n // The initial replay may have settled us above, before `unsubscribe` existed;\n // `stop()`'s deferred read picks it up, so nothing more is needed here.\n if (!settled && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (settled) return;\n stop();\n const err = new Error(\n `waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`,\n ) as SpaceError;\n err.code = 'timeout';\n reject(err);\n }, timeoutMs);\n }\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: 'session-mounts',\n requestType: 'request-session-mounts',\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (\n listener: (mounts: SessionMount[]) => void,\n): (() => void) => sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** Summary of a space, as returned by {@link listSpaces}. */\nexport interface SpaceInfo {\n spaceId: string;\n role?: 'owner' | 'writer' | 'reader';\n owner?: string;\n name?: string;\n}\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n // Client-side, never from the host: a bounded `waitForMount` gave up.\n | 'timeout'\n | 'unknown';\n}\n\ntype SpaceResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('spaces', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (\n method: string,\n query: Record<string, unknown>,\n): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> =>\n requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> =>\n mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> =>\n requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n */\nexport const makeContentRef = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('settings', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway: an unbounded wait\n // here turns any delivery failure into a promise that never settles, and every\n // caller of `openSettings()` is doing it to reach durable state — so the app\n // just quietly loses that state with nothing to report.\n return waitForMount({ id: mount.id ?? mount.path }, SETTINGS_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openSettings()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst SETTINGS_MOUNT_TIMEOUT_MS = 15_000;\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> =>\n settingsRequest<string[]>('list');\n\n/** Create a brand-new, empty platform-hosted space. The app reaches it (or any\n * other space) afterward through the {@link requestMount} powerbox or\n * {@link mountSpace}; there is no implicit per-app binding. */\nexport const createSpace = (\n opts: { name?: string } = {}\n): Promise<SandboxMount> => requestMountInternal('create', opts);\n\n/** List spaces you can access — all of them, or just those bound to this app. */\nexport const listSpaces = (opts: { app?: boolean } = {}): Promise<SpaceInfo[]> =>\n request<SpaceInfo[]>('list', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A collaborator's role on a shared space: full `owner`, read-write `writer`, or read-only `reader`. */\nexport type Role = 'owner' | 'writer' | 'reader';\n\n/** A member of a space (for the share/manage UI). */\nexport interface Member {\n /**\n * The **grantee** — `user:{uid}` | `group:{gid}`. This is the canonical name\n * (core_concepts §4: \"principal\" is reserved for the authority context; a space\n * member is a *grantee*). The host populates this on every member row.\n */\n grantee: string;\n /**\n * @deprecated Use {@link Member.grantee}. Kept as an alias (same value) for\n * back-compat during the `principal`→`grantee` migration; will be removed in a\n * future major. The host still populates both.\n */\n principal: string;\n role: Role;\n login?: string;\n avatarUrl?: string;\n}\n\n/** A handle resolved to a principal (handle → who). */\nexport interface ResolvedUser {\n uid: string;\n login: string;\n avatarUrl?: string;\n}\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** Enumerate ALL the user's spaces (not just this app's) — `spaces:user`. */\nexport const listAllSpaces = (): Promise<SpaceInfo[]> => request<SpaceInfo[]>('listAll', {});\n\n/** Read a space's members one-shot — `spaces:admin`. */\nexport const getSpaceMembers = (spaceId: string): Promise<Member[]> =>\n request<Member[]>('members', { spaceId });\n\n/** Invite a user (by provider handle) to a space at a role — `spaces:admin`. The\n * host resolves the handle, so the app never sees other users' uids except the one\n * it invited. Pull-based (FILE_SHARING_SPEC §6.4): this writes an INVITATION, not\n * membership — the recipient must {@link acceptInvite}. Re-inviting an already-\n * invited/member user is idempotent. */\nexport const inviteToSpace = async (spaceId: string, login: string, role: Role): Promise<void> => {\n await request('invite', { spaceId, login, role });\n};\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: 'invitations',\n requestType: 'request-invitations',\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n/** Remove a member from a space — `spaces:admin`. Refused if it would orphan the\n * space (owner-lockout, T41). */\nexport const unshareSpace = async (spaceId: string, uid: string): Promise<void> => {\n await request('unshare', { spaceId, uid });\n};\n\n/** Change a member's role — `spaces:admin`. Refused if it would drop the sole\n * owner (owner-lockout, T41). */\nexport const setSpaceRole = async (spaceId: string, uid: string, role: Role): Promise<void> => {\n await request('setRole', { spaceId, uid, role });\n};\n\n/** Resolve a provider handle to a principal (for the invite flow) — `spaces:admin`,\n * rate-limited host-side. */\nexport const lookupUser = (login: string): Promise<ResolvedUser> =>\n request<ResolvedUser>('lookupUser', { login });\n\n/** One durable grant an app holds, for the §8.11 capability audit view. */\nexport interface GrantRecord {\n /** The app's provider-qualified **program** identity (AA-01 `appKey`). The DEFAULT\n * program keys to the bare `provider__namespace__repository`; a NAMED mini-app\n * appends a fourth `enc()`-escaped component (`provider__namespace__repository__name`)\n * so its grants isolate from the repo's other programs. Host-supplied — the app\n * never builds this key. */\n appKey: string;\n spaceId: string;\n /** Universal mount id (§3.5). */\n mountId: string;\n subtree?: string;\n mode: 'ro' | 'rw';\n name?: string;\n}\n\n/** Enumerate every (app, mount) grant the user holds — the audit view\n * (§8.11). Elevated `spaces:admin`. */\nexport const listGrants = (): Promise<GrantRecord[]> => request<GrantRecord[]>('grants', {});\n\n/** Revoke one app's grant on a space — durable (the app can't re-mount) plus a\n * best-effort live teardown. Elevated `spaces:admin`. */\nexport const revokeGrant = async (appKey: string, spaceId: string): Promise<void> => {\n await request('revokeGrant', { appKey, spaceId });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAoC;AACpC,0BAA0D;AAC1D,yBAAkC;AAClC,yBAA+B;AAC/B,wBAA6B;AAatB,MAAM,kBAAkB,UAAc,mCAAe,GAAG,gBAAgB;AAoF/E,MAAM,WAAW,CAAC,MAA4B,EAAE,MAAM,EAAE;AAExD,MAAM,uBAA4C,oBAAI,IAAuB;AAAA,EAC3E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,sBAAsB,CAAC,UAC3B,OAAO,UAAU,YAAY,qBAA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,MAAM,aAAa,CAAC,UACzB,QAAsB,cAAc,EAAE,MAAM,CAAC;AAoBxC,MAAM,aAAa,MAA8B,QAAuB,UAAU,CAAC,CAAC;AAIpF,MAAM,cAAc,OAAO,QAAgB,YAAmC;AACnF,QAAM,QAAQ,eAAe,EAAE,QAAQ,QAAQ,CAAC;AAClD;","names":["mount"]}
|
package/dist/mounts.d.cts
CHANGED
|
@@ -103,8 +103,29 @@ declare const onMountsChange: (listener: (mounts: SandboxMount[], removed: Remov
|
|
|
103
103
|
* Resolves once a mount matching `query` is present (immediately if it already
|
|
104
104
|
* is). Handy for "use it when it appears" — e.g.
|
|
105
105
|
* `await waitForMount({ type: 'firestore' })` before reading `/firestore`.
|
|
106
|
+
*
|
|
107
|
+
* `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of
|
|
108
|
+
* waiting forever. Omit it to keep the original unbounded behaviour — but prefer
|
|
109
|
+
* setting it on any path whose caller would otherwise hang silently: a mount that
|
|
110
|
+
* never arrives is indistinguishable from one that is merely slow, and an awaited
|
|
111
|
+
* promise that never settles surfaces to the user as a feature that quietly does
|
|
112
|
+
* nothing.
|
|
113
|
+
*
|
|
114
|
+
* **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the
|
|
115
|
+
* documented initial replay). So when the mount is already present — the common
|
|
116
|
+
* case, since callers typically `await` the host request that creates it first —
|
|
117
|
+
* the callback below runs *during* the `onMountsChange(...)` call, before the
|
|
118
|
+
* assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with
|
|
119
|
+
* `let` ABOVE the subscription and read only inside a deferred closure: writing
|
|
120
|
+
* `const unsubscribe = onMountsChange(...)` and referencing it in the callback
|
|
121
|
+
* throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a
|
|
122
|
+
* temporal-dead-zone read) on exactly that path. That bug silently broke
|
|
123
|
+
* `openSettings()` — and with it the agent's conversation memory.
|
|
106
124
|
*/
|
|
107
|
-
declare const waitForMount: (query: MountQuery) => Promise<SandboxMount>;
|
|
125
|
+
declare const waitForMount: (query: MountQuery, timeoutMs?: number) => Promise<SandboxMount>;
|
|
126
|
+
/** The framework-free core of {@link waitForMount}, with the subscription injected
|
|
127
|
+
* so a test can drive the synchronous-initial-replay case that broke it. */
|
|
128
|
+
declare const awaitMatchingMount: (subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void, query: MountQuery, timeoutMs?: number) => Promise<SandboxMount>;
|
|
108
129
|
/** React hook returning the mounts currently available, re-rendering on change. */
|
|
109
130
|
declare const useMounts: () => SandboxMount[];
|
|
110
131
|
/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):
|
|
@@ -138,7 +159,7 @@ interface SpaceInfo {
|
|
|
138
159
|
}
|
|
139
160
|
/** An error from a space operation, carrying a machine-readable `code`. */
|
|
140
161
|
interface SpaceError extends Error {
|
|
141
|
-
code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'unsupported-scheme' | 'unknown';
|
|
162
|
+
code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'unsupported-scheme' | 'timeout' | 'unknown';
|
|
142
163
|
}
|
|
143
164
|
/**
|
|
144
165
|
* Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —
|
|
@@ -374,7 +395,11 @@ declare const setSpaceRole: (spaceId: string, uid: string, role: Role) => Promis
|
|
|
374
395
|
declare const lookupUser: (login: string) => Promise<ResolvedUser>;
|
|
375
396
|
/** One durable grant an app holds, for the §8.11 capability audit view. */
|
|
376
397
|
interface GrantRecord {
|
|
377
|
-
/** The app's provider-qualified identity (`
|
|
398
|
+
/** The app's provider-qualified **program** identity (AA-01 `appKey`). The DEFAULT
|
|
399
|
+
* program keys to the bare `provider__namespace__repository`; a NAMED mini-app
|
|
400
|
+
* appends a fourth `enc()`-escaped component (`provider__namespace__repository__name`)
|
|
401
|
+
* so its grants isolate from the repo's other programs. Host-supplied — the app
|
|
402
|
+
* never builds this key. */
|
|
378
403
|
appKey: string;
|
|
379
404
|
spaceId: string;
|
|
380
405
|
/** Universal mount id (§3.5). */
|
|
@@ -390,4 +415,4 @@ declare const listGrants: () => Promise<GrantRecord[]>;
|
|
|
390
415
|
* best-effort live teardown. Elevated `spaces:admin`. */
|
|
391
416
|
declare const revokeGrant: (appKey: string, spaceId: string) => Promise<void>;
|
|
392
417
|
|
|
393
|
-
export { type GrantRecord, type Invite, type Member, type MountQuery, type MountRemoveReason, type MountRule, type RemovedMount, type ResolvedUser, type Role, type SandboxMount, type SessionMount, type SpaceError, type SpaceInfo, acceptInvite, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount };
|
|
418
|
+
export { type GrantRecord, type Invite, type Member, type MountQuery, type MountRemoveReason, type MountRule, type RemovedMount, type ResolvedUser, type Role, type SandboxMount, type SessionMount, type SpaceError, type SpaceInfo, acceptInvite, awaitMatchingMount, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount };
|
package/dist/mounts.d.ts
CHANGED
|
@@ -103,8 +103,29 @@ declare const onMountsChange: (listener: (mounts: SandboxMount[], removed: Remov
|
|
|
103
103
|
* Resolves once a mount matching `query` is present (immediately if it already
|
|
104
104
|
* is). Handy for "use it when it appears" — e.g.
|
|
105
105
|
* `await waitForMount({ type: 'firestore' })` before reading `/firestore`.
|
|
106
|
+
*
|
|
107
|
+
* `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of
|
|
108
|
+
* waiting forever. Omit it to keep the original unbounded behaviour — but prefer
|
|
109
|
+
* setting it on any path whose caller would otherwise hang silently: a mount that
|
|
110
|
+
* never arrives is indistinguishable from one that is merely slow, and an awaited
|
|
111
|
+
* promise that never settles surfaces to the user as a feature that quietly does
|
|
112
|
+
* nothing.
|
|
113
|
+
*
|
|
114
|
+
* **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the
|
|
115
|
+
* documented initial replay). So when the mount is already present — the common
|
|
116
|
+
* case, since callers typically `await` the host request that creates it first —
|
|
117
|
+
* the callback below runs *during* the `onMountsChange(...)` call, before the
|
|
118
|
+
* assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with
|
|
119
|
+
* `let` ABOVE the subscription and read only inside a deferred closure: writing
|
|
120
|
+
* `const unsubscribe = onMountsChange(...)` and referencing it in the callback
|
|
121
|
+
* throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a
|
|
122
|
+
* temporal-dead-zone read) on exactly that path. That bug silently broke
|
|
123
|
+
* `openSettings()` — and with it the agent's conversation memory.
|
|
106
124
|
*/
|
|
107
|
-
declare const waitForMount: (query: MountQuery) => Promise<SandboxMount>;
|
|
125
|
+
declare const waitForMount: (query: MountQuery, timeoutMs?: number) => Promise<SandboxMount>;
|
|
126
|
+
/** The framework-free core of {@link waitForMount}, with the subscription injected
|
|
127
|
+
* so a test can drive the synchronous-initial-replay case that broke it. */
|
|
128
|
+
declare const awaitMatchingMount: (subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void, query: MountQuery, timeoutMs?: number) => Promise<SandboxMount>;
|
|
108
129
|
/** React hook returning the mounts currently available, re-rendering on change. */
|
|
109
130
|
declare const useMounts: () => SandboxMount[];
|
|
110
131
|
/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):
|
|
@@ -138,7 +159,7 @@ interface SpaceInfo {
|
|
|
138
159
|
}
|
|
139
160
|
/** An error from a space operation, carrying a machine-readable `code`. */
|
|
140
161
|
interface SpaceError extends Error {
|
|
141
|
-
code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'unsupported-scheme' | 'unknown';
|
|
162
|
+
code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'unsupported-scheme' | 'timeout' | 'unknown';
|
|
142
163
|
}
|
|
143
164
|
/**
|
|
144
165
|
* Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —
|
|
@@ -374,7 +395,11 @@ declare const setSpaceRole: (spaceId: string, uid: string, role: Role) => Promis
|
|
|
374
395
|
declare const lookupUser: (login: string) => Promise<ResolvedUser>;
|
|
375
396
|
/** One durable grant an app holds, for the §8.11 capability audit view. */
|
|
376
397
|
interface GrantRecord {
|
|
377
|
-
/** The app's provider-qualified identity (`
|
|
398
|
+
/** The app's provider-qualified **program** identity (AA-01 `appKey`). The DEFAULT
|
|
399
|
+
* program keys to the bare `provider__namespace__repository`; a NAMED mini-app
|
|
400
|
+
* appends a fourth `enc()`-escaped component (`provider__namespace__repository__name`)
|
|
401
|
+
* so its grants isolate from the repo's other programs. Host-supplied — the app
|
|
402
|
+
* never builds this key. */
|
|
378
403
|
appKey: string;
|
|
379
404
|
spaceId: string;
|
|
380
405
|
/** Universal mount id (§3.5). */
|
|
@@ -390,4 +415,4 @@ declare const listGrants: () => Promise<GrantRecord[]>;
|
|
|
390
415
|
* best-effort live teardown. Elevated `spaces:admin`. */
|
|
391
416
|
declare const revokeGrant: (appKey: string, spaceId: string) => Promise<void>;
|
|
392
417
|
|
|
393
|
-
export { type GrantRecord, type Invite, type Member, type MountQuery, type MountRemoveReason, type MountRule, type RemovedMount, type ResolvedUser, type Role, type SandboxMount, type SessionMount, type SpaceError, type SpaceInfo, acceptInvite, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount };
|
|
418
|
+
export { type GrantRecord, type Invite, type Member, type MountQuery, type MountRemoveReason, type MountRule, type RemovedMount, type ResolvedUser, type Role, type SandboxMount, type SessionMount, type SpaceError, type SpaceInfo, acceptInvite, awaitMatchingMount, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount };
|
package/dist/mounts.js
CHANGED
|
@@ -68,14 +68,35 @@ const onMountsChange = (listener) => {
|
|
|
68
68
|
const disposable = mountService().onChange(listener);
|
|
69
69
|
return () => disposable.dispose();
|
|
70
70
|
};
|
|
71
|
-
const waitForMount = (query) =>
|
|
72
|
-
|
|
71
|
+
const waitForMount = (query, timeoutMs) => awaitMatchingMount(onMountsChange, query, timeoutMs);
|
|
72
|
+
const awaitMatchingMount = (subscribe, query, timeoutMs) => new Promise((resolve, reject) => {
|
|
73
|
+
let unsubscribe;
|
|
74
|
+
let settled = false;
|
|
75
|
+
let timer;
|
|
76
|
+
const stop = () => {
|
|
77
|
+
settled = true;
|
|
78
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
79
|
+
void Promise.resolve().then(() => unsubscribe?.());
|
|
80
|
+
};
|
|
81
|
+
unsubscribe = subscribe((mounts) => {
|
|
82
|
+
if (settled) return;
|
|
73
83
|
const found = mounts.find((m) => matches(m, query));
|
|
74
84
|
if (found) {
|
|
75
|
-
|
|
85
|
+
stop();
|
|
76
86
|
resolve(found);
|
|
77
87
|
}
|
|
78
88
|
});
|
|
89
|
+
if (!settled && timeoutMs !== void 0) {
|
|
90
|
+
timer = setTimeout(() => {
|
|
91
|
+
if (settled) return;
|
|
92
|
+
stop();
|
|
93
|
+
const err = new Error(
|
|
94
|
+
`waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`
|
|
95
|
+
);
|
|
96
|
+
err.code = "timeout";
|
|
97
|
+
reject(err);
|
|
98
|
+
}, timeoutMs);
|
|
99
|
+
}
|
|
79
100
|
});
|
|
80
101
|
const useMounts = () => {
|
|
81
102
|
const [mounts, setMounts] = useState(getMounts);
|
|
@@ -128,8 +149,9 @@ const settingsRequest = async (method, query = {}) => {
|
|
|
128
149
|
};
|
|
129
150
|
const openSettings = async () => {
|
|
130
151
|
const mount2 = await settingsRequest("open");
|
|
131
|
-
return waitForMount({ id: mount2.id ?? mount2.path });
|
|
152
|
+
return waitForMount({ id: mount2.id ?? mount2.path }, SETTINGS_MOUNT_TIMEOUT_MS);
|
|
132
153
|
};
|
|
154
|
+
const SETTINGS_MOUNT_TIMEOUT_MS = 15e3;
|
|
133
155
|
const importSettingsFromParent = async () => {
|
|
134
156
|
try {
|
|
135
157
|
const data = await settingsRequest("importFromParent");
|
|
@@ -186,6 +208,7 @@ const revokeGrant = async (appKey, spaceId) => {
|
|
|
186
208
|
};
|
|
187
209
|
export {
|
|
188
210
|
acceptInvite,
|
|
211
|
+
awaitMatchingMount,
|
|
189
212
|
createSpace,
|
|
190
213
|
declineInvite,
|
|
191
214
|
findMount,
|
package/dist/mounts.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? '/app';\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: \"ro\" | \"rw\";\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason =\n | \"revoked\"\n | \"unshared\"\n | \"signed-out\"\n | \"unmounted\"\n | \"deleted\";\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n ): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value)\n ? (value as MountRemoveReason)\n : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener('mount-add', (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener('mount-remove', (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage('request-mounts');\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean =>\n mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined =>\n getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n */\nexport const waitForMount = (query: MountQuery): Promise<SandboxMount> =>\n new Promise((resolve) => {\n const unsubscribe = onMountsChange((mounts) => {\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n // Defer unsubscribe so we don't dispose during the initial replay call.\n Promise.resolve().then(unsubscribe);\n resolve(found);\n }\n });\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: 'session-mounts',\n requestType: 'request-session-mounts',\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (\n listener: (mounts: SessionMount[]) => void,\n): (() => void) => sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** Summary of a space, as returned by {@link listSpaces}. */\nexport interface SpaceInfo {\n spaceId: string;\n role?: 'owner' | 'writer' | 'reader';\n owner?: string;\n name?: string;\n}\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n | 'unknown';\n}\n\ntype SpaceResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('spaces', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (\n method: string,\n query: Record<string, unknown>,\n): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> =>\n requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> =>\n mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> =>\n requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n */\nexport const makeContentRef = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('settings', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> =>\n settingsRequest<string[]>('list');\n\n/** Create a brand-new, empty platform-hosted space. The app reaches it (or any\n * other space) afterward through the {@link requestMount} powerbox or\n * {@link mountSpace}; there is no implicit per-app binding. */\nexport const createSpace = (\n opts: { name?: string } = {}\n): Promise<SandboxMount> => requestMountInternal('create', opts);\n\n/** List spaces you can access — all of them, or just those bound to this app. */\nexport const listSpaces = (opts: { app?: boolean } = {}): Promise<SpaceInfo[]> =>\n request<SpaceInfo[]>('list', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A collaborator's role on a shared space: full `owner`, read-write `writer`, or read-only `reader`. */\nexport type Role = 'owner' | 'writer' | 'reader';\n\n/** A member of a space (for the share/manage UI). */\nexport interface Member {\n /**\n * The **grantee** — `user:{uid}` | `group:{gid}`. This is the canonical name\n * (core_concepts §4: \"principal\" is reserved for the authority context; a space\n * member is a *grantee*). The host populates this on every member row.\n */\n grantee: string;\n /**\n * @deprecated Use {@link Member.grantee}. Kept as an alias (same value) for\n * back-compat during the `principal`→`grantee` migration; will be removed in a\n * future major. The host still populates both.\n */\n principal: string;\n role: Role;\n login?: string;\n avatarUrl?: string;\n}\n\n/** A handle resolved to a principal (handle → who). */\nexport interface ResolvedUser {\n uid: string;\n login: string;\n avatarUrl?: string;\n}\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** Enumerate ALL the user's spaces (not just this app's) — `spaces:user`. */\nexport const listAllSpaces = (): Promise<SpaceInfo[]> => request<SpaceInfo[]>('listAll', {});\n\n/** Read a space's members one-shot — `spaces:admin`. */\nexport const getSpaceMembers = (spaceId: string): Promise<Member[]> =>\n request<Member[]>('members', { spaceId });\n\n/** Invite a user (by provider handle) to a space at a role — `spaces:admin`. The\n * host resolves the handle, so the app never sees other users' uids except the one\n * it invited. Pull-based (FILE_SHARING_SPEC §6.4): this writes an INVITATION, not\n * membership — the recipient must {@link acceptInvite}. Re-inviting an already-\n * invited/member user is idempotent. */\nexport const inviteToSpace = async (spaceId: string, login: string, role: Role): Promise<void> => {\n await request('invite', { spaceId, login, role });\n};\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: 'invitations',\n requestType: 'request-invitations',\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n/** Remove a member from a space — `spaces:admin`. Refused if it would orphan the\n * space (owner-lockout, T41). */\nexport const unshareSpace = async (spaceId: string, uid: string): Promise<void> => {\n await request('unshare', { spaceId, uid });\n};\n\n/** Change a member's role — `spaces:admin`. Refused if it would drop the sole\n * owner (owner-lockout, T41). */\nexport const setSpaceRole = async (spaceId: string, uid: string, role: Role): Promise<void> => {\n await request('setRole', { spaceId, uid, role });\n};\n\n/** Resolve a provider handle to a principal (for the invite flow) — `spaces:admin`,\n * rate-limited host-side. */\nexport const lookupUser = (login: string): Promise<ResolvedUser> =>\n request<ResolvedUser>('lookupUser', { login });\n\n/** One durable grant an app holds, for the §8.11 capability audit view. */\nexport interface GrantRecord {\n /** The app's provider-qualified identity (`provider__namespace__repository`). */\n appKey: string;\n spaceId: string;\n /** Universal mount id (§3.5). */\n mountId: string;\n subtree?: string;\n mode: 'ro' | 'rw';\n name?: string;\n}\n\n/** Enumerate every (app, mount) grant the user holds — the audit view\n * (§8.11). Elevated `spaces:admin`. */\nexport const listGrants = (): Promise<GrantRecord[]> => request<GrantRecord[]>('grants', {});\n\n/** Revoke one app's grant on a space — durable (the app can't re-mount) plus a\n * best-effort live teardown. Elevated `spaces:admin`. */\nexport const revokeGrant = async (appKey: string, spaceId: string): Promise<void> => {\n await request('revokeGrant', { appKey, spaceId });\n};\n"],"mappings":";AAAA,SAAS,WAAW,gBAAgB;AACpC,SAAS,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C;AAClD;","names":["mount"]}
|
|
1
|
+
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? '/app';\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: \"ro\" | \"rw\";\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason =\n | \"revoked\"\n | \"unshared\"\n | \"signed-out\"\n | \"unmounted\"\n | \"deleted\";\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n ): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value)\n ? (value as MountRemoveReason)\n : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener('mount-add', (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener('mount-remove', (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage('request-mounts');\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean =>\n mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined =>\n getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n *\n * `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of\n * waiting forever. Omit it to keep the original unbounded behaviour — but prefer\n * setting it on any path whose caller would otherwise hang silently: a mount that\n * never arrives is indistinguishable from one that is merely slow, and an awaited\n * promise that never settles surfaces to the user as a feature that quietly does\n * nothing.\n *\n * **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the\n * documented initial replay). So when the mount is already present — the common\n * case, since callers typically `await` the host request that creates it first —\n * the callback below runs *during* the `onMountsChange(...)` call, before the\n * assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with\n * `let` ABOVE the subscription and read only inside a deferred closure: writing\n * `const unsubscribe = onMountsChange(...)` and referencing it in the callback\n * throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a\n * temporal-dead-zone read) on exactly that path. That bug silently broke\n * `openSettings()` — and with it the agent's conversation memory.\n */\nexport const waitForMount = (\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> => awaitMatchingMount(onMountsChange, query, timeoutMs);\n\n/** The framework-free core of {@link waitForMount}, with the subscription injected\n * so a test can drive the synchronous-initial-replay case that broke it. */\nexport const awaitMatchingMount = (\n subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void,\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> =>\n new Promise((resolve, reject) => {\n // `let`, declared BEFORE `subscribe(...)` — see the hazard note above. A\n // `const` bound to the subscribe call is in its temporal dead zone while the\n // synchronous initial replay runs, and any read of it from the listener\n // throws.\n let unsubscribe: (() => void) | undefined;\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // Deferred so we never dispose the subscription from inside its own initial\n // replay, and late enough that `unsubscribe` is always assigned.\n const stop = (): void => {\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n void Promise.resolve().then(() => unsubscribe?.());\n };\n unsubscribe = subscribe((mounts) => {\n if (settled) return;\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n stop();\n resolve(found);\n }\n });\n // The initial replay may have settled us above, before `unsubscribe` existed;\n // `stop()`'s deferred read picks it up, so nothing more is needed here.\n if (!settled && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (settled) return;\n stop();\n const err = new Error(\n `waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`,\n ) as SpaceError;\n err.code = 'timeout';\n reject(err);\n }, timeoutMs);\n }\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: 'session-mounts',\n requestType: 'request-session-mounts',\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (\n listener: (mounts: SessionMount[]) => void,\n): (() => void) => sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** Summary of a space, as returned by {@link listSpaces}. */\nexport interface SpaceInfo {\n spaceId: string;\n role?: 'owner' | 'writer' | 'reader';\n owner?: string;\n name?: string;\n}\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n // Client-side, never from the host: a bounded `waitForMount` gave up.\n | 'timeout'\n | 'unknown';\n}\n\ntype SpaceResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('spaces', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (\n method: string,\n query: Record<string, unknown>,\n): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> =>\n requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> =>\n mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> =>\n requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n */\nexport const makeContentRef = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('settings', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway: an unbounded wait\n // here turns any delivery failure into a promise that never settles, and every\n // caller of `openSettings()` is doing it to reach durable state — so the app\n // just quietly loses that state with nothing to report.\n return waitForMount({ id: mount.id ?? mount.path }, SETTINGS_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openSettings()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst SETTINGS_MOUNT_TIMEOUT_MS = 15_000;\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> =>\n settingsRequest<string[]>('list');\n\n/** Create a brand-new, empty platform-hosted space. The app reaches it (or any\n * other space) afterward through the {@link requestMount} powerbox or\n * {@link mountSpace}; there is no implicit per-app binding. */\nexport const createSpace = (\n opts: { name?: string } = {}\n): Promise<SandboxMount> => requestMountInternal('create', opts);\n\n/** List spaces you can access — all of them, or just those bound to this app. */\nexport const listSpaces = (opts: { app?: boolean } = {}): Promise<SpaceInfo[]> =>\n request<SpaceInfo[]>('list', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A collaborator's role on a shared space: full `owner`, read-write `writer`, or read-only `reader`. */\nexport type Role = 'owner' | 'writer' | 'reader';\n\n/** A member of a space (for the share/manage UI). */\nexport interface Member {\n /**\n * The **grantee** — `user:{uid}` | `group:{gid}`. This is the canonical name\n * (core_concepts §4: \"principal\" is reserved for the authority context; a space\n * member is a *grantee*). The host populates this on every member row.\n */\n grantee: string;\n /**\n * @deprecated Use {@link Member.grantee}. Kept as an alias (same value) for\n * back-compat during the `principal`→`grantee` migration; will be removed in a\n * future major. The host still populates both.\n */\n principal: string;\n role: Role;\n login?: string;\n avatarUrl?: string;\n}\n\n/** A handle resolved to a principal (handle → who). */\nexport interface ResolvedUser {\n uid: string;\n login: string;\n avatarUrl?: string;\n}\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** Enumerate ALL the user's spaces (not just this app's) — `spaces:user`. */\nexport const listAllSpaces = (): Promise<SpaceInfo[]> => request<SpaceInfo[]>('listAll', {});\n\n/** Read a space's members one-shot — `spaces:admin`. */\nexport const getSpaceMembers = (spaceId: string): Promise<Member[]> =>\n request<Member[]>('members', { spaceId });\n\n/** Invite a user (by provider handle) to a space at a role — `spaces:admin`. The\n * host resolves the handle, so the app never sees other users' uids except the one\n * it invited. Pull-based (FILE_SHARING_SPEC §6.4): this writes an INVITATION, not\n * membership — the recipient must {@link acceptInvite}. Re-inviting an already-\n * invited/member user is idempotent. */\nexport const inviteToSpace = async (spaceId: string, login: string, role: Role): Promise<void> => {\n await request('invite', { spaceId, login, role });\n};\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: 'invitations',\n requestType: 'request-invitations',\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n/** Remove a member from a space — `spaces:admin`. Refused if it would orphan the\n * space (owner-lockout, T41). */\nexport const unshareSpace = async (spaceId: string, uid: string): Promise<void> => {\n await request('unshare', { spaceId, uid });\n};\n\n/** Change a member's role — `spaces:admin`. Refused if it would drop the sole\n * owner (owner-lockout, T41). */\nexport const setSpaceRole = async (spaceId: string, uid: string, role: Role): Promise<void> => {\n await request('setRole', { spaceId, uid, role });\n};\n\n/** Resolve a provider handle to a principal (for the invite flow) — `spaces:admin`,\n * rate-limited host-side. */\nexport const lookupUser = (login: string): Promise<ResolvedUser> =>\n request<ResolvedUser>('lookupUser', { login });\n\n/** One durable grant an app holds, for the §8.11 capability audit view. */\nexport interface GrantRecord {\n /** The app's provider-qualified **program** identity (AA-01 `appKey`). The DEFAULT\n * program keys to the bare `provider__namespace__repository`; a NAMED mini-app\n * appends a fourth `enc()`-escaped component (`provider__namespace__repository__name`)\n * so its grants isolate from the repo's other programs. Host-supplied — the app\n * never builds this key. */\n appKey: string;\n spaceId: string;\n /** Universal mount id (§3.5). */\n mountId: string;\n subtree?: string;\n mode: 'ro' | 'rw';\n name?: string;\n}\n\n/** Enumerate every (app, mount) grant the user holds — the audit view\n * (§8.11). Elevated `spaces:admin`. */\nexport const listGrants = (): Promise<GrantRecord[]> => request<GrantRecord[]>('grants', {});\n\n/** Revoke one app's grant on a space — durable (the app can't re-mount) plus a\n * best-effort live teardown. Elevated `spaces:admin`. */\nexport const revokeGrant = async (appKey: string, spaceId: string): Promise<void> => {\n await request('revokeGrant', { appKey, spaceId });\n};\n"],"mappings":";AAAA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAatB,MAAM,kBAAkB,MAAc,eAAe,GAAG,gBAAgB;AAoF/E,MAAM,WAAW,CAAC,MAA4B,EAAE,MAAM,EAAE;AAExD,MAAM,uBAA4C,oBAAI,IAAuB;AAAA,EAC3E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,sBAAsB,CAAC,UAC3B,OAAO,UAAU,YAAY,qBAAqB,IAAI,KAAK,IACtD,QACD;AAKN,MAAM,uBAAuB,MAA2B;AACtD,MAAI;AAEF,UAAM,MAAM,QAAQ,YAAY,QAAQ,SAAS;AACjD,WAAO,OAAO,OAAO,IAAI,cAAc,aAAa,MAAM;AAAA,EAC5D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAUA,IAAI,eAAoC;AAExC,MAAM,wBAAwB,MAAoB;AAChD,MAAI,aAAc,QAAO;AACzB,MAAI,SAAyB,CAAC;AAC9B,QAAM,YAAY,oBAAI,IAAoD;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.exports = __toCommonJS(version_exports);
|
|
24
|
-
const SDK_VERSION = "0.
|
|
24
|
+
const SDK_VERSION = "0.37.0";
|
|
25
25
|
// Annotate the CommonJS export names for ESM import in node:
|
|
26
26
|
0 && (module.exports = {
|
|
27
27
|
SDK_VERSION
|
package/dist/version.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.37.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,MAAM,cAAc;","names":[]}
|
package/dist/version.d.cts
CHANGED
package/dist/version.d.ts
CHANGED
package/dist/version.js
CHANGED
package/dist/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.37.0';\n"],"mappings":";AAIO,MAAM,cAAc;","names":[]}
|
package/package.json
CHANGED