@sanity-labs/client-fake-for-test 0.31.0 → 0.33.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.cjs CHANGED
@@ -1076,6 +1076,21 @@ async function readHistory(args) {
1076
1076
  }
1077
1077
  };
1078
1078
  }
1079
+ function permissionRecords(args) {
1080
+ const { ctx, resource } = args, entries = Object.entries(ctx.actorAccess() ?? {}), own = accessKey(resource.type, resource.id);
1081
+ return (resource.type === "organization" && resource.id === ctx.organizationId ? entries : entries.filter(([key]) => key === own)).flatMap(([key, entry]) => {
1082
+ const separator = key.indexOf(":"), resourceType = key.slice(0, separator), resourceId = key.slice(separator + 1);
1083
+ return (entry.permissions ?? []).map((permission) => {
1084
+ const dot = permission.lastIndexOf(".");
1085
+ return {
1086
+ type: permission.slice(0, dot),
1087
+ resourceType,
1088
+ resourceId,
1089
+ action: permission.slice(dot + 1)
1090
+ };
1091
+ });
1092
+ });
1093
+ }
1079
1094
  function serveGated(args) {
1080
1095
  const { capability, permission, held, request, serve } = args;
1081
1096
  return serveCapability(capability, request, () => {
@@ -1155,19 +1170,7 @@ function serveAccess(args) {
1155
1170
  value: usersPage(usersOn({ resource, registry, identities: ctx.identities() }))
1156
1171
  }));
1157
1172
  case "/user-permissions/me":
1158
- return {
1159
- value: page(
1160
- permissions.map((permission) => {
1161
- const dot = permission.lastIndexOf(".");
1162
- return {
1163
- type: permission.slice(0, dot),
1164
- resourceType: resource.type,
1165
- resourceId: id,
1166
- action: permission.slice(dot + 1)
1167
- };
1168
- })
1169
- )
1170
- };
1173
+ return { value: page(permissionRecords({ ctx, resource })) };
1171
1174
  default:
1172
1175
  return;
1173
1176
  }
@@ -2218,6 +2221,179 @@ async function applyActions(store, actions, hooks) {
2218
2221
  throw err;
2219
2222
  }
2220
2223
  }
2224
+ function openListener(args) {
2225
+ const { organizationId, spec, readable, open, signal } = args, tree = groqJs.parse(spec.query, { params: spec.params }), encoder = new TextEncoder();
2226
+ let listener;
2227
+ const close = () => {
2228
+ listener !== void 0 && open.delete(listener);
2229
+ }, body = new ReadableStream({
2230
+ start: (controller) => {
2231
+ let ended = !1;
2232
+ const write = (text) => {
2233
+ ended || controller.enqueue(encoder.encode(text));
2234
+ }, end = () => {
2235
+ ended || (ended = !0, close(), controller.close());
2236
+ }, sees = async (document) => {
2237
+ if (document === void 0 || !await readable(document)) return !1;
2238
+ const result = await (await groqJs.evaluate(tree, { dataset: [document], params: spec.params })).get();
2239
+ return Array.isArray(result) ? result.length > 0 : result !== null && result !== !1;
2240
+ };
2241
+ listener = {
2242
+ organizationId,
2243
+ deliver: async (commit) => {
2244
+ const events = [];
2245
+ for (const change of commit.changes) {
2246
+ const transition = transitionOf(await sees(change.before), await sees(change.after));
2247
+ transition !== void 0 && events.push({ change, transition });
2248
+ }
2249
+ events.forEach(
2250
+ ({ change, transition }, index) => write(
2251
+ mutationFrame({
2252
+ spec,
2253
+ commit,
2254
+ change,
2255
+ transition,
2256
+ position: { current: index + 1, total: events.length }
2257
+ })
2258
+ )
2259
+ );
2260
+ },
2261
+ fail: (error) => {
2262
+ write(`event: channelError
2263
+ data: ${JSON.stringify({ error })}
2264
+
2265
+ `), write(`event: disconnect
2266
+ data: {"reason": "error"}
2267
+
2268
+ `), end();
2269
+ },
2270
+ drop: end
2271
+ }, open.add(listener), write(`:
2272
+
2273
+ `), write(`event: welcome
2274
+ data: ${JSON.stringify({ listenerName: listenerName() })}
2275
+
2276
+ `), signal?.addEventListener("abort", close);
2277
+ },
2278
+ cancel: close
2279
+ });
2280
+ return new Response(body, {
2281
+ status: 200,
2282
+ headers: { "content-type": "text/event-stream", "cache-control": "no-cache" }
2283
+ });
2284
+ }
2285
+ function transitionOf(before, after) {
2286
+ return before ? after ? "update" : "disappear" : after ? "appear" : void 0;
2287
+ }
2288
+ function mutationFrame(args) {
2289
+ const { spec, commit, change, transition, position } = args, eventId = `${commit.transactionId}#${change.id}`, now = (/* @__PURE__ */ new Date()).toISOString(), data = {
2290
+ eventId,
2291
+ documentId: change.id,
2292
+ transactionId: commit.transactionId,
2293
+ transition,
2294
+ ...commit.identity !== void 0 ? { identity: commit.identity } : {},
2295
+ ...spec.includeMutations ? { mutations: mutationsOf(change) } : {},
2296
+ ...spec.includePreviousRevision && change.before !== void 0 ? { previous: change.before } : {},
2297
+ ...spec.includeResult && change.after !== void 0 ? { result: change.after } : {},
2298
+ ...change.before !== void 0 ? { previousRev: change.before._rev } : {},
2299
+ ...change.after !== void 0 ? { resultRev: change.after._rev } : {},
2300
+ timestamp: now,
2301
+ visibility: spec.visibility,
2302
+ transactionCurrentEvent: position.current,
2303
+ transactionTotalEvents: position.total,
2304
+ messageDispatchedAt: now
2305
+ };
2306
+ return `event: mutation
2307
+ id: ${eventId}
2308
+ data: ${JSON.stringify(data)}
2309
+
2310
+ `;
2311
+ }
2312
+ function mutationsOf(change) {
2313
+ return change.after === void 0 ? [{ delete: { id: change.id } }] : [{ createOrReplace: change.after }];
2314
+ }
2315
+ let listenerCount = 0;
2316
+ function listenerName() {
2317
+ return listenerCount += 1, `listener-${listenerCount}`;
2318
+ }
2319
+ class ListenerRefusal extends Error {
2320
+ error;
2321
+ constructor(error) {
2322
+ super(error.description), this.error = error;
2323
+ }
2324
+ }
2325
+ const KNOWN_PARAMETERS = /* @__PURE__ */ new Set([
2326
+ "query",
2327
+ "visibility",
2328
+ "includeResult",
2329
+ "includeMutations",
2330
+ "includeProjection",
2331
+ "includePreviousRevision",
2332
+ "effectFormat",
2333
+ "includeAllVersions",
2334
+ "lastEventId",
2335
+ "enableResume",
2336
+ "evs_preamble",
2337
+ "evs_buffer_size_limit",
2338
+ "evs_last_event_id",
2339
+ "tag",
2340
+ "access_token",
2341
+ "debug"
2342
+ ]), UNMODELLED = ["includeProjection", "effectFormat", "includeAllVersions", "enableResume"];
2343
+ function listenerSpec(search) {
2344
+ const unknown = [...new Set(search.keys())].filter(
2345
+ (name) => !name.startsWith("$") && !KNOWN_PARAMETERS.has(name)
2346
+ );
2347
+ if (unknown.length > 0)
2348
+ throw new ListenerRefusal({
2349
+ type: "httpUnknownQueryStringParameters",
2350
+ description: unknown.length === 1 ? `Unknown query parameter ${JSON.stringify(unknown[0])}` : `Unknown query parameters: ${unknown.map((name) => JSON.stringify(name)).join(", ")}`,
2351
+ names: unknown
2352
+ });
2353
+ const unmodelled = UNMODELLED.find((name) => search.has(name));
2354
+ if (unmodelled !== void 0)
2355
+ throw fakeError(`resolveFetch(): the listener option \`${unmodelled}\` is not modelled.`);
2356
+ const query = search.getAll("query");
2357
+ if (query.length > 1)
2358
+ throw new ListenerRefusal({
2359
+ type: "validationError",
2360
+ description: "query can only occur once"
2361
+ });
2362
+ if (query[0] === void 0)
2363
+ throw fakeError("resolveFetch(): a listener needs a `query` parameter.");
2364
+ const visibility = search.get("visibility") ?? "transaction";
2365
+ if (visibility !== "transaction" && visibility !== "query")
2366
+ throw new ListenerRefusal({
2367
+ type: "validationError",
2368
+ description: `invalid listener visibility ${JSON.stringify(visibility)}`
2369
+ });
2370
+ const flag = (name) => search.has(name) && search.get(name) !== "false";
2371
+ return {
2372
+ query: query[0],
2373
+ params: Object.fromEntries(
2374
+ [...search].filter(([name]) => name.startsWith("$")).map(([name, value]) => [name.slice(1), JSON.parse(value)])
2375
+ ),
2376
+ includeResult: flag("includeResult"),
2377
+ includePreviousRevision: flag("includePreviousRevision"),
2378
+ includeMutations: !search.has("includeMutations") || flag("includeMutations"),
2379
+ visibility
2380
+ };
2381
+ }
2382
+ function refusedListener(error) {
2383
+ return new Response(fatalFrames(error), {
2384
+ status: 200,
2385
+ headers: { "content-type": "text/event-stream" }
2386
+ });
2387
+ }
2388
+ function fatalFrames(error) {
2389
+ return `event: channelError
2390
+ data: ${JSON.stringify({ error })}
2391
+
2392
+ event: disconnect
2393
+ data: {"reason": "error"}
2394
+
2395
+ `;
2396
+ }
2221
2397
  function createTransaction(executor) {
2222
2398
  const mutations = [], handle = {
2223
2399
  create: (doc) => (mutations.push({ kind: "create", doc }), handle),
@@ -2290,6 +2466,25 @@ function encodeGroqQuery(query, params = {}) {
2290
2466
  value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
2291
2467
  return `?${search}`;
2292
2468
  }
2469
+ function handledRequest(options) {
2470
+ const full = new URL(options.url ?? ""), [, version, ...path] = full.pathname.split("/");
2471
+ if (version === void 0 || !version.startsWith("v"))
2472
+ throw fakeError(`requestHandler(): "${options.url}" has no /v<apiVersion> segment.`);
2473
+ const entries = options.query instanceof URLSearchParams ? [...options.query] : Object.entries(options.query ?? {}), search = new URLSearchParams(full.search);
2474
+ let tag;
2475
+ for (const [key, value] of entries)
2476
+ key === "tag" && typeof value == "string" ? tag = value : value !== void 0 && search.append(key, String(value));
2477
+ const query = search.toString(), bearer = new Headers(options.headers).get("authorization") ?? void 0;
2478
+ return {
2479
+ apiHost: `${full.protocol}//${full.host}`,
2480
+ apiVersion: version.slice(1),
2481
+ url: `/${path.join("/")}${query === "" ? "" : `?${query}`}`,
2482
+ method: options.method?.toUpperCase() === "POST" ? "POST" : "GET",
2483
+ token: bearer?.replace(/^Bearer /, ""),
2484
+ body: options.body,
2485
+ tag
2486
+ };
2487
+ }
2293
2488
  const SIGNING_METHODS = /* @__PURE__ */ new Set([
2294
2489
  ...["HS", "RS", "PS", "ES"].flatMap((family) => ["256", "384", "512"].map((n) => family + n)),
2295
2490
  "EdDSA",
@@ -2780,6 +2975,76 @@ function storeNotFound(request, identifier) {
2780
2975
  }
2781
2976
  });
2782
2977
  }
2978
+ function unauthorizedOrganization(request) {
2979
+ return new PlatformHttpError({
2980
+ ...request,
2981
+ statusCode: 403,
2982
+ statusMessage: "Forbidden",
2983
+ body: {
2984
+ error: { type: "permissionDeniedError", description: "Unauthorized organization access" }
2985
+ }
2986
+ });
2987
+ }
2988
+ function failingMutation(args) {
2989
+ const held = new Set(args.revisions.keys()), written = /* @__PURE__ */ new Set();
2990
+ for (const mutation of args.mutations) {
2991
+ const refusal2 = refusalOf({ ...args, held, written, mutation });
2992
+ if (refusal2 !== void 0) return refusal2;
2993
+ }
2994
+ }
2995
+ function refusalOf(args) {
2996
+ const { request, revisions, held, written, mutation } = args, created = mutation.create ?? mutation.createOrReplace ?? mutation.createIfNotExists;
2997
+ if (created !== void 0) {
2998
+ const id2 = String(created._id);
2999
+ if (mutation.create !== void 0 && held.has(id2))
3000
+ return mutationError(request, 409, {
3001
+ type: "documentAlreadyExistsError",
3002
+ description: `Document by ID ${goQuoted(id2)} already exists`,
3003
+ id: id2
3004
+ });
3005
+ held.add(id2), written.add(id2);
3006
+ return;
3007
+ }
3008
+ if (mutation.delete !== void 0) {
3009
+ held.delete(String(mutation.delete.id));
3010
+ return;
3011
+ }
3012
+ if (mutation.patch === void 0) return;
3013
+ const id = String(mutation.patch.id);
3014
+ if (!held.has(id))
3015
+ return mutationError(request, 404, {
3016
+ type: "documentNotFoundError",
3017
+ description: `The document with the ID ${goQuoted(id)} was not found`,
3018
+ id
3019
+ });
3020
+ const expected = mutation.patch.ifRevisionID;
3021
+ if (typeof expected == "string" && expected !== "") {
3022
+ if (written.has(id))
3023
+ throw fakeError(
3024
+ `request(): a mutate body patches "${id}" with ifRevisionID after writing it; the revision gradient gives a document mid-transaction is not modelled.`
3025
+ );
3026
+ const current = revisions.get(id) ?? "";
3027
+ if (expected !== current)
3028
+ return mutationError(request, 409, {
3029
+ type: "documentRevisionIDDoesNotMatchError",
3030
+ description: `Document ${goQuoted(id)} has unexpected revision ID (${goQuoted(current)}), expected ${goQuoted(expected)}`,
3031
+ expectedRevisionID: expected,
3032
+ currentRevisionID: current
3033
+ });
3034
+ }
3035
+ written.add(id);
3036
+ }
3037
+ function mutationError(request, statusCode, error) {
3038
+ return new PlatformHttpError({
3039
+ ...request,
3040
+ statusCode,
3041
+ statusMessage: statusCode === 404 ? "Not Found" : "Conflict",
3042
+ body: { error }
3043
+ });
3044
+ }
3045
+ function goQuoted(text) {
3046
+ return JSON.stringify(text);
3047
+ }
2783
3048
  const OPTIONS_ARG_POSITION = {
2784
3049
  fetch: 2,
2785
3050
  getDocument: 1,
@@ -2799,7 +3064,10 @@ function tagFromArgs(method, args) {
2799
3064
  if (!(typeof options != "object" || options === null || !("tag" in options)))
2800
3065
  return options.tag;
2801
3066
  }
2802
- const RECORDED_METHODS = /* @__PURE__ */ new Set([
3067
+ function mutatedId(mutation) {
3068
+ return mutation.kind === "delete" ? mutation.id : mutation.kind === "patch" ? mutation.documentId : String(mutation.doc._id);
3069
+ }
3070
+ const handleListeners = /* @__PURE__ */ new WeakMap(), RECORDED_METHODS = /* @__PURE__ */ new Set([
2803
3071
  "fetch",
2804
3072
  "getDocument",
2805
3073
  "getDocuments",
@@ -2888,6 +3156,14 @@ async function serveStoreAction(args) {
2888
3156
  const body = opts.body;
2889
3157
  if (!Array.isArray(body?.mutations))
2890
3158
  throw fakeError(`request(): POST "${sent.path}" needs a body \`{ mutations: [...] }\`.`);
3159
+ const refusal2 = failingMutation({
3160
+ request: sent,
3161
+ revisions: new Map(
3162
+ client$1.store().all().map((doc) => [doc._id, doc._rev])
3163
+ ),
3164
+ mutations: body.mutations
3165
+ });
3166
+ if (refusal2 !== void 0) throw refusal2;
2891
3167
  const committed = await client$1.mutate(body.mutations, {
2892
3168
  returnDocuments: !1,
2893
3169
  returnFirst: !1,
@@ -2995,6 +3271,7 @@ function createTestClient(options = {}) {
2995
3271
  internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
2996
3272
  internalTokens: /* @__PURE__ */ new Map(),
2997
3273
  outages: /* @__PURE__ */ new Set(),
3274
+ listeners: /* @__PURE__ */ new Set(),
2998
3275
  missingDatasets: new Set(options.missingDatasets ?? []),
2999
3276
  writeChain: Promise.resolve()
3000
3277
  }, registry = backend.registry;
@@ -3165,11 +3442,17 @@ function makeHandle(handleArgs) {
3165
3442
  sent,
3166
3443
  routed.route === "read" ? `org:${routed.organizationId}` : routed.storeId
3167
3444
  );
3445
+ if (routed.route === "read" && routed.action === "listen")
3446
+ throw fakeError(
3447
+ `request(): "${sent.path}" is a listener, which \`request()\` does not open. Open it through \`resolveFetch()\`, as \`@sanity/client\` opens a listener.`
3448
+ );
3168
3449
  const servedActions = routed.route === "read" ? ["query", "doc"] : ["query", "doc", "mutate"];
3169
3450
  if (!servedActions.includes(routed.action))
3170
3451
  throw fakeError(
3171
3452
  `request(): "${sent.path}" is ${routed.action} on the organization store; the fake serves ${servedActions.join(", ")} there.`
3172
3453
  );
3454
+ const scope = token === void 0 ? void 0 : backend.identities.get(token)?.organizationScope;
3455
+ if (scope !== void 0 && scope !== store2.organizationId) throw unauthorizedOrganization(sent);
3173
3456
  const onStore = makeHandle({
3174
3457
  ...handleArgs,
3175
3458
  resource: void 0,
@@ -3190,6 +3473,61 @@ function makeHandle(handleArgs) {
3190
3473
  sent,
3191
3474
  opts
3192
3475
  });
3476
+ }, listen = (url, init) => {
3477
+ const sent = { method: "GET", path: url.pathname, url: url.href };
3478
+ try {
3479
+ if (handleArgs.internalStore !== void 0) return streamListener(sent, url, init);
3480
+ refuseSession2(sent);
3481
+ const [, version = "", ...rest] = url.pathname.split("/"), path = `/${rest.join("/")}`, routed = matchWorkflowsStoreRoute({ path, apiVersion: version.slice(1) });
3482
+ if (routed === "unrouted") throw noRouteMatched({ ...sent, path });
3483
+ if (typeof routed != "object" || routed.route !== "read" || routed.action !== "listen")
3484
+ throw fakeError(
3485
+ `resolveFetch(): "${url.href}" is not the Workflows store read route's listen, the only URL it serves.`
3486
+ );
3487
+ const store2 = activeStoreOf(routed.organizationId);
3488
+ if (store2 === void 0) throw storeNotFound(sent, `org:${routed.organizationId}`);
3489
+ const scope = token === void 0 ? void 0 : backend.identities.get(token)?.organizationScope;
3490
+ if (scope !== void 0 && scope !== store2.organizationId)
3491
+ throw unauthorizedOrganization(sent);
3492
+ const onStore = makeHandle({
3493
+ ...handleArgs,
3494
+ resource: void 0,
3495
+ useProjectHostname: !1,
3496
+ perspective: "raw",
3497
+ configuredPerspective: void 0,
3498
+ internalStore: {
3499
+ resource: { type: "organization-store", id: store2.id },
3500
+ store: { id: store2.id, organizationId: store2.organizationId }
3501
+ }
3502
+ });
3503
+ return handleListeners.get(onStore)(url, init);
3504
+ } catch (error) {
3505
+ if (!(error instanceof PlatformHttpError)) throw error;
3506
+ return new Response(JSON.stringify(error.response.body), {
3507
+ status: error.response.statusCode,
3508
+ headers: { "content-type": "application/json; charset=utf-8" }
3509
+ });
3510
+ }
3511
+ }, streamListener = (sent, url, init) => {
3512
+ admitToLake(sent);
3513
+ let spec;
3514
+ try {
3515
+ spec = listenerSpec(url.searchParams), parseQuery(sent, spec.query, spec.params);
3516
+ } catch (error) {
3517
+ if (error instanceof ListenerRefusal) return refusedListener(error.error);
3518
+ if (error instanceof PlatformHttpError)
3519
+ return refusedListener(error.response.body.error);
3520
+ if (error instanceof groqJs.GroqSyntaxError)
3521
+ return refusedListener({ type: "queryParseError", description: error.message });
3522
+ throw error;
3523
+ }
3524
+ return openListener({
3525
+ organizationId: handleArgs.internalStore.store.organizationId,
3526
+ spec,
3527
+ readable: canRead,
3528
+ open: backend.listeners,
3529
+ signal: init?.signal
3530
+ });
3193
3531
  }, activeStoreOf = (organizationId) => {
3194
3532
  const store2 = backend.organizationStores.get(organizationId);
3195
3533
  return store2?.status === "active" ? store2 : void 0;
@@ -3302,11 +3640,18 @@ function makeHandle(handleArgs) {
3302
3640
  } finally {
3303
3641
  beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
3304
3642
  }
3305
- }), commitHistory = (transactionId) => {
3306
- beforeWrite !== void 0 && (targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() }));
3643
+ }), commitHistory = (transactionId, touched = []) => {
3644
+ if (beforeWrite === void 0) return;
3645
+ targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
3646
+ const organizationId = handleArgs.internalStore?.store.organizationId;
3647
+ organizationId !== void 0 && notifyListeners({ organizationId, transactionId, touched, before: beforeWrite });
3648
+ }, notifyListeners = (args) => {
3649
+ const after = new Map(store.all().map((doc) => [doc._id, doc])), changes = [.../* @__PURE__ */ new Set([...args.touched, ...args.before.keys(), ...after.keys()])].filter((id) => args.before.get(id) !== after.get(id)).map((id) => ({ id, before: args.before.get(id), after: after.get(id) })), commit = { transactionId: args.transactionId, identity: actorId(), changes };
3650
+ for (const listener of backend.listeners)
3651
+ listener.organizationId === args.organizationId && listener.deliver(commit);
3307
3652
  }, record = (transactionId, mutations, tag) => {
3308
3653
  const effectiveTag = effectiveRequestTag(tag);
3309
- commitHistory(transactionId), backend.log.push({
3654
+ commitHistory(transactionId, mutations.map(mutatedId)), backend.log.push({
3310
3655
  transactionId,
3311
3656
  projectId,
3312
3657
  dataset,
@@ -3813,6 +4158,36 @@ function makeHandle(handleArgs) {
3813
4158
  );
3814
4159
  return ensureEntry(registry, { type: "organization-store", id: organizationStore.id }).store;
3815
4160
  },
4161
+ requestHandler: () => (options) => {
4162
+ const sent = handledRequest(options), sibling = client2.withConfig({
4163
+ ...sent.token !== void 0 ? { token: sent.token } : {},
4164
+ apiHost: sent.apiHost,
4165
+ apiVersion: sent.apiVersion,
4166
+ useProjectHostname: !1
4167
+ });
4168
+ if (sibling.request === void 0)
4169
+ throw fakeError(
4170
+ "requestHandler(): the request carries no token the fake knows, so it has no `request()` to answer it."
4171
+ );
4172
+ return sibling.request({
4173
+ url: sent.url,
4174
+ method: sent.method,
4175
+ ...sent.body !== void 0 ? { body: sent.body } : {},
4176
+ ...sent.tag !== void 0 ? { tag: sent.tag } : {}
4177
+ });
4178
+ },
4179
+ resolveFetch: () => () => async (input, init) => {
4180
+ const url = new URL(String(input)), bearer = new Headers(init?.headers).get("authorization")?.replace(/^Bearer /, "");
4181
+ return bearer === void 0 ? listen(url, init) : handleListeners.get(client2.withConfig({ token: bearer }))(url, init);
4182
+ },
4183
+ failListeners: (organizationId, error) => {
4184
+ for (const listener of backend.listeners)
4185
+ listener.organizationId === organizationId && listener.fail(error);
4186
+ },
4187
+ dropListeners: (organizationId) => {
4188
+ for (const listener of backend.listeners)
4189
+ listener.organizationId === organizationId && listener.drop();
4190
+ },
3816
4191
  addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
3817
4192
  removeFunction: (id) => unregisterFunction(backend.functions, id),
3818
4193
  functionInvocations: () => structuredClone(backend.functions.invocations),
@@ -3826,8 +4201,7 @@ function makeHandle(handleArgs) {
3826
4201
  clearCalls: () => {
3827
4202
  backend.calls.length = 0;
3828
4203
  }
3829
- };
3830
- return wrapWithGuards(client2, {
4204
+ }, wrapped = wrapWithGuards(client2, {
3831
4205
  getStub: (name) => backend.stubs.get(name),
3832
4206
  onCall: (method, args) => {
3833
4207
  const rec = {
@@ -3845,6 +4219,7 @@ function makeHandle(handleArgs) {
3845
4219
  },
3846
4220
  recorded: handleArgs.internalStore === void 0 ? RECORDED_METHODS : /* @__PURE__ */ new Set()
3847
4221
  });
4222
+ return handleListeners.set(wrapped, listen), wrapped;
3848
4223
  }
3849
4224
  exports.ERR_PREFIX = ERR_PREFIX;
3850
4225
  exports.GuardDeniedError = GuardDeniedError;
@@ -3866,6 +4241,7 @@ exports.isDraftId = isDraftId;
3866
4241
  exports.isReleaseDocId = isReleaseDocId;
3867
4242
  exports.isSystemId = isSystemId;
3868
4243
  exports.isVersionId = isVersionId;
4244
+ exports.organizationStoreId = organizationStoreId;
3869
4245
  exports.publishedIdOf = publishedIdOf;
3870
4246
  exports.releaseNameOf = releaseNameOf;
3871
4247
  exports.wrapWithGuards = wrapWithGuards;