@frontmcp/sdk 1.12.2 → 1.12.3

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.
Files changed (89) hide show
  1. package/app/instances/app.lazy.instance.d.ts.map +1 -1
  2. package/app/lazy/lazy-app.rules.d.ts +5 -0
  3. package/app/lazy/lazy-app.rules.d.ts.map +1 -1
  4. package/auth/flows/oauth.authorize.flow.d.ts +2 -0
  5. package/auth/flows/oauth.authorize.flow.d.ts.map +1 -1
  6. package/auth/flows/oauth.callback.flow.d.ts +1 -0
  7. package/auth/flows/oauth.callback.flow.d.ts.map +1 -1
  8. package/auth/flows/oauth.provider-callback.flow.d.ts +1 -0
  9. package/auth/flows/oauth.provider-callback.flow.d.ts.map +1 -1
  10. package/auth/flows/session.verify.flow.d.ts +2 -0
  11. package/auth/flows/session.verify.flow.d.ts.map +1 -1
  12. package/auth/instances/instance.local-primary-auth.d.ts +9 -4
  13. package/auth/instances/instance.local-primary-auth.d.ts.map +1 -1
  14. package/auth/instances/instance.remote-primary-auth.d.ts +2 -0
  15. package/auth/instances/instance.remote-primary-auth.d.ts.map +1 -1
  16. package/auth/session-scope-identity.d.ts +5 -3
  17. package/auth/session-scope-identity.d.ts.map +1 -1
  18. package/browser/app/instances/app.lazy.instance.mjs +9 -2
  19. package/browser/app/lazy/lazy-app.rules.mjs +11 -1
  20. package/browser/auth/flows/oauth.authorize.flow.mjs +7 -1
  21. package/browser/auth/flows/oauth.callback.flow.mjs +6 -2
  22. package/browser/auth/flows/oauth.provider-callback.flow.mjs +8 -4
  23. package/browser/auth/flows/session.verify.flow.mjs +17 -14
  24. package/browser/auth/instances/instance.local-primary-auth.mjs +46 -12
  25. package/browser/auth/instances/instance.remote-primary-auth.mjs +13 -1
  26. package/browser/auth/session-scope-identity.mjs +6 -1
  27. package/browser/common/interfaces/flow.interface.mjs +7 -1
  28. package/browser/common/types/auth/session.types.mjs +2 -1
  29. package/browser/common/utils/auth-info.utils.mjs +3 -2
  30. package/browser/flows/flow.instance.mjs +43 -5
  31. package/browser/hooks/hooks.utils.mjs +10 -4
  32. package/browser/index.cjs +1342 -1116
  33. package/browser/notification/notification.service.mjs +28 -4
  34. package/browser/notification/resource-update-access.mjs +22 -0
  35. package/browser/plugin/enforced-metadata.check.mjs +2 -1
  36. package/browser/prompt/flows/get-prompt.flow.mjs +13 -0
  37. package/browser/remote-mcp/mcp-client.service.mjs +26 -13
  38. package/browser/remote-mcp/remote-request-headers.mjs +6 -3
  39. package/browser/resource/flows/read-resource.flow.mjs +20 -23
  40. package/browser/resource/flows/subscribe-resource.flow.mjs +9 -4
  41. package/browser/tool/ui/ui-shared.mjs +9 -0
  42. package/browser/transport/flows/handle.mcp-20260728.flow.mjs +9 -3
  43. package/browser/transport/mcp-20260728/index.mjs +1 -1
  44. package/browser/transport/mcp-20260728/subscriptions.mjs +8 -6
  45. package/common/interfaces/flow.interface.d.ts +4 -1
  46. package/common/interfaces/flow.interface.d.ts.map +1 -1
  47. package/common/metadata/app.metadata.d.ts +16 -16
  48. package/common/metadata/front-mcp.metadata.d.ts +37 -37
  49. package/common/types/auth/session.types.d.ts +6 -0
  50. package/common/types/auth/session.types.d.ts.map +1 -1
  51. package/common/types/options/http/interfaces.d.ts +4 -1
  52. package/common/types/options/http/interfaces.d.ts.map +1 -1
  53. package/common/utils/auth-info.utils.d.ts +1 -0
  54. package/common/utils/auth-info.utils.d.ts.map +1 -1
  55. package/esm/index.mjs +24 -24
  56. package/flows/flow.instance.d.ts.map +1 -1
  57. package/hooks/hooks.utils.d.ts +2 -4
  58. package/hooks/hooks.utils.d.ts.map +1 -1
  59. package/index.d.ts +5 -5
  60. package/index.js +35 -35
  61. package/notification/notification.service.d.ts +7 -2
  62. package/notification/notification.service.d.ts.map +1 -1
  63. package/notification/resource-update-access.d.ts +9 -0
  64. package/notification/resource-update-access.d.ts.map +1 -0
  65. package/package.json +10 -10
  66. package/plugin/enforced-metadata.check.d.ts +3 -1
  67. package/plugin/enforced-metadata.check.d.ts.map +1 -1
  68. package/prompt/flows/get-prompt.flow.d.ts +3 -1
  69. package/prompt/flows/get-prompt.flow.d.ts.map +1 -1
  70. package/remote-mcp/mcp-client.service.d.ts.map +1 -1
  71. package/remote-mcp/mcp-client.types.d.ts.map +1 -1
  72. package/remote-mcp/remote-request-headers.d.ts +22 -8
  73. package/remote-mcp/remote-request-headers.d.ts.map +1 -1
  74. package/resource/flows/read-resource.flow.d.ts +2 -0
  75. package/resource/flows/read-resource.flow.d.ts.map +1 -1
  76. package/resource/flows/subscribe-resource.flow.d.ts.map +1 -1
  77. package/scope/flows/http.request.flow.d.ts +1 -0
  78. package/scope/flows/http.request.flow.d.ts.map +1 -1
  79. package/server/adapters/express.host.adapter.d.ts +3 -2
  80. package/server/adapters/express.host.adapter.d.ts.map +1 -1
  81. package/shared/shared-endpoint.d.ts +5 -1
  82. package/shared/shared-endpoint.d.ts.map +1 -1
  83. package/shared/unix-socket-fetch.d.ts +7 -0
  84. package/shared/unix-socket-fetch.d.ts.map +1 -1
  85. package/tool/ui/ui-shared.d.ts +4 -0
  86. package/tool/ui/ui-shared.d.ts.map +1 -1
  87. package/transport/flows/handle.mcp-20260728.flow.d.ts.map +1 -1
  88. package/transport/mcp-20260728/subscriptions.d.ts +5 -3
  89. package/transport/mcp-20260728/subscriptions.d.ts.map +1 -1
@@ -10,6 +10,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
10
10
 
11
11
  // libs/sdk/src/auth/instances/instance.local-primary-auth.ts
12
12
  import {
13
+ clientAuthMethodToRecord,
13
14
  createSecureStore,
14
15
  createTokenStorageAdapter,
15
16
  DcrClientRegistry,
@@ -24,6 +25,7 @@ import {
24
25
  isSqliteTokenStorage,
25
26
  JwksService,
26
27
  LocalTokenKeys,
28
+ meetsRecordedClientAuth,
27
29
  resolveUpstreamClient,
28
30
  SessionCredentialVault,
29
31
  StorageAuthorizationStore,
@@ -436,8 +438,9 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
436
438
  * adapter-backed equivalents. For `'memory'` (or unset) this is a no-op, so
437
439
  * the default behavior is preserved exactly.
438
440
  *
439
- * The orchestrated-token store keeps using the JWT secret as its encryption
440
- * key, so upstream provider tokens stay encrypted at rest in every backend.
441
+ * The orchestrated-token and federated-session stores use the JWT secret as
442
+ * their encryption key, so upstream provider tokens stay encrypted at rest in
443
+ * every backend.
441
444
  */
442
445
  async initializeStores() {
443
446
  if (!isPersistentTokenStorage(this.tokenStorage)) {
@@ -449,10 +452,11 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
449
452
  this.storageClosers.push(() => adapter.disconnect());
450
453
  this.disposeInMemoryStores();
451
454
  this.authorizationStoreImpl = new StorageAuthorizationStore(adapter);
452
- this.federatedSessionStoreImpl = new StorageFederatedAuthSessionStore(adapter);
455
+ this.federatedSessionStoreImpl = new StorageFederatedAuthSessionStore(adapter, { encryptionKey: this.secret });
453
456
  this.orchestratedTokenStoreImpl = new StorageOrchestratedTokenStore(adapter, {
454
457
  encryptionKey: this.secret,
455
- refreshSkewMs: this.providerRefreshSkewMs()
458
+ refreshSkewMs: this.providerRefreshSkewMs(),
459
+ providerIssuer: (providerId) => this.providerAuthorizationServer(providerId)
456
460
  });
457
461
  this.consentStoreImpl = new StorageConsentStore(adapter);
458
462
  const backend = isSqliteTokenStorage(this.tokenStorage) ? "sqlite" : isRedisTokenStorage(this.tokenStorage) ? "redis" : "unknown";
@@ -821,6 +825,10 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
821
825
  error_description: "Client ID does not match"
822
826
  };
823
827
  }
828
+ if (!meetsRecordedClientAuth(codeRecord.clientAuthMethod, declared.authMethod)) {
829
+ this.logger.warn("Authorization code needs client authentication this client did not provide");
830
+ return { error: "invalid_client", error_description: "Client authentication failed" };
831
+ }
824
832
  if (codeRecord.redirectUri !== redirectUri) {
825
833
  this.logger.warn(`Redirect URI mismatch`);
826
834
  return {
@@ -886,7 +894,8 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
886
894
  federatedLoginUsed: codeRecord.federatedLoginUsed,
887
895
  selectedProviderIds: codeRecord.selectedProviderIds,
888
896
  skippedProviderIds: codeRecord.skippedProviderIds,
889
- providerTokensId
897
+ providerTokensId,
898
+ clientAuthMethod: clientAuthMethodToRecord(codeRecord.clientAuthMethod, declared.authMethod)
890
899
  });
891
900
  await this.authorizationStore.storeRefreshToken(refreshTokenRecord);
892
901
  await this.authorizationStore.markCodeUsed(code, refreshTokenRecord.token);
@@ -895,11 +904,13 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
895
904
  /**
896
905
  * Refuse a grant the client did not declare in its `grant_types` (RFC 7591): in its registration, its
897
906
  * `dcr.clients` entry or its client ID metadata document. A client that declared nothing (an unregistered
898
- * id under `requireRegisteredClients: false`) is not limited, and gets `grantTypes: undefined`. A CIMD client
899
- * whose document declares `private_key_jwt` must also present a valid client assertion.
907
+ * id under `requireRegisteredClients: false`, or one registered on another instance or before a restart)
908
+ * is not limited, and gets `grantTypes: undefined` and `authMethod: undefined`. A CIMD client whose document
909
+ * declares `private_key_jwt` must also present a valid client assertion.
900
910
  */
901
911
  async checkDeclaredGrant(clientId, grantType, clientAssertion) {
902
912
  let grantTypes;
913
+ let authMethod;
903
914
  try {
904
915
  const cimd = this.cimdService;
905
916
  if (cimd?.enabled && cimd.isCimdClientId(clientId)) {
@@ -913,8 +924,11 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
913
924
  });
914
925
  }
915
926
  grantTypes = metadata?.grant_types;
927
+ authMethod = metadata?.token_endpoint_auth_method ?? "none";
916
928
  } else {
917
- grantTypes = this.dcrClientRegistryImpl.get(clientId)?.grant_types;
929
+ const registered = this.dcrClientRegistryImpl.get(clientId);
930
+ grantTypes = registered?.grant_types;
931
+ authMethod = registered?.token_endpoint_auth_method;
918
932
  }
919
933
  } catch (err) {
920
934
  this.logger.warn(`Client metadata refused at token endpoint (${grantType}): ${err.message}`);
@@ -924,7 +938,7 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
924
938
  this.logger.warn(`Client did not declare the ${grantType} grant`);
925
939
  return { error: "unauthorized_client", error_description: `This client may not use the ${grantType} grant` };
926
940
  }
927
- return { grantTypes };
941
+ return { grantTypes, authMethod };
928
942
  }
929
943
  /**
930
944
  * Move the upstream provider tokens stored under `fromAuthorizationId` to the authorization id of
@@ -996,6 +1010,10 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
996
1010
  error_description: "Client ID does not match"
997
1011
  };
998
1012
  }
1013
+ if (!meetsRecordedClientAuth(tokenRecord.clientAuthMethod, declared.authMethod)) {
1014
+ this.logger.warn("Refresh token needs client authentication this client did not provide");
1015
+ return { error: "invalid_client", error_description: "Client authentication failed" };
1016
+ }
999
1017
  const user = {
1000
1018
  sub: tokenRecord.userSub,
1001
1019
  email: tokenRecord.userEmail,
@@ -1035,7 +1053,8 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1035
1053
  federatedLoginUsed: tokenRecord.federatedLoginUsed,
1036
1054
  selectedProviderIds: tokenRecord.selectedProviderIds,
1037
1055
  skippedProviderIds: tokenRecord.skippedProviderIds,
1038
- providerTokensId: copiedTo ?? sourceId
1056
+ providerTokensId: copiedTo ?? sourceId,
1057
+ clientAuthMethod: clientAuthMethodToRecord(tokenRecord.clientAuthMethod, declared.authMethod)
1039
1058
  });
1040
1059
  try {
1041
1060
  await this.authorizationStore.rotateRefreshToken(refreshToken, newRefreshRecord);
@@ -1086,7 +1105,8 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1086
1105
  // Progressive/Incremental authorization: granted app-id set.
1087
1106
  authorizedAppIds: params.authorizedAppIds,
1088
1107
  // Custom claims from a local authenticate() verifier (Checkpoint 3a)
1089
- customClaims: params.customClaims
1108
+ customClaims: params.customClaims,
1109
+ clientAuthMethod: params.clientAuthMethod
1090
1110
  });
1091
1111
  await this.authorizationStore.storeAuthorizationCode(codeRecord);
1092
1112
  this.logger.info(`Authorization code created for user: ${params.userSub}`);
@@ -1158,6 +1178,14 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1158
1178
  this.providerConfigs.set(config.id, config);
1159
1179
  this.logger.info(`Registered upstream provider: ${config.id}`);
1160
1180
  }
1181
+ /** The authorization server a provider's tokens come from: its issuer, else its token endpoint. */
1182
+ providerAuthorizationServer(providerId) {
1183
+ const config = this.providerConfigs.get(providerId);
1184
+ if (!config) {
1185
+ return void 0;
1186
+ }
1187
+ return config.issuer ? normalizeIssuer(config.issuer) : config.tokenEndpoint;
1188
+ }
1161
1189
  /**
1162
1190
  * Drop every stored credential for a provider whose authorization server changed.
1163
1191
  *
@@ -1559,6 +1587,7 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1559
1587
  };
1560
1588
  }
1561
1589
  async renewProviderToken(providerId, refreshToken) {
1590
+ const issuer = this.providerAuthorizationServer(providerId);
1562
1591
  const result = await this.refreshProviderToken(providerId, refreshToken);
1563
1592
  if ("error" in result || typeof result.access_token !== "string" || !result.access_token) {
1564
1593
  this.logger.warn(
@@ -1568,7 +1597,12 @@ var LocalPrimaryAuth = class extends FrontMcpAuth {
1568
1597
  `Provider "${providerId}" did not refresh its token; the user has to sign in again`
1569
1598
  );
1570
1599
  }
1571
- return { accessToken: result.access_token, refreshToken: result.refresh_token, expiresIn: result.expires_in };
1600
+ return {
1601
+ accessToken: result.access_token,
1602
+ refreshToken: result.refresh_token,
1603
+ expiresIn: result.expires_in,
1604
+ issuer
1605
+ };
1572
1606
  }
1573
1607
  /** How long before its expiry a provider token is renewed: `refresh.skewSeconds` (default 60), none with `refresh` off. */
1574
1608
  providerRefreshSkewMs() {
@@ -1,6 +1,6 @@
1
1
  // libs/sdk/src/auth/instances/instance.remote-primary-auth.ts
2
2
  import { JwksService } from "@frontmcp/auth";
3
- import { FrontMcpAuth, ProviderScope } from "../../common/index.mjs";
3
+ import { FrontMcpAuth, isPublicUrlPinned, ProviderScope } from "../../common/index.mjs";
4
4
  import SessionVerifyFlow from "../flows/session.verify.flow.mjs";
5
5
  import WellKnownJwksFlow from "../flows/well-known.jwks.flow.mjs";
6
6
  import WellKnownAsFlow from "../flows/well-known.oauth-authorization-server.flow.mjs";
@@ -36,8 +36,20 @@ var RemotePrimaryAuth = class extends FrontMcpAuth {
36
36
  provide: JwksService
37
37
  });
38
38
  await this.registerAuthFlows(scope);
39
+ this.warnWithoutConfiguredAudience(scope);
39
40
  return Promise.resolve();
40
41
  }
42
+ /** Warn once at startup when nothing configures the token audience, so the request host decides it. */
43
+ warnWithoutConfiguredAudience(scope) {
44
+ const protection = scope.metadata.http?.security?.dnsRebindingProtection;
45
+ const checkedHosts = protection?.enabled === false ? void 0 : protection?.allowedHosts;
46
+ if (this.options.expectedAudience || isPublicUrlPinned() || checkedHosts?.length) {
47
+ return;
48
+ }
49
+ scope.logger.warn(
50
+ "Transparent auth has no configured token audience, so each token is checked against the host the request names. Set auth.expectedAudience to the audience your identity provider puts in tokens (or set FRONTMCP_PUBLIC_URL, or list the server host in security.dnsRebindingProtection.allowedHosts with that protection on). FrontMCP 1.13 will refuse tokens that carry an aud claim when none of these is set."
51
+ );
52
+ }
41
53
  async registerAuthFlows(scope) {
42
54
  await scope.registryFlows(
43
55
  WellKnownPrmFlow,
@@ -8,7 +8,12 @@ function sessionScopeIdentity(ctx) {
8
8
  const principal = [authInfo.user?.sub, extraUser?.sub, authInfo.clientId].find(
9
9
  (candidate) => !isAnonymousSubject(candidate)
10
10
  );
11
- return principal ? `principal:${principal}` : void 0;
11
+ if (!principal) return void 0;
12
+ const principalIssuer = authInfo.extra?.["principalIssuer"];
13
+ if (typeof principalIssuer === "string") {
14
+ return `issuer-principal:${encodeURIComponent(principalIssuer)}:${principal}`;
15
+ }
16
+ return `principal:${principal}`;
12
17
  }
13
18
  export {
14
19
  sessionScopeIdentity
@@ -50,12 +50,13 @@ var FlowControl = class _FlowControl extends Error {
50
50
  };
51
51
  brandClass(FlowControl, "@frontmcp/sdk:FlowControl");
52
52
  var FlowBase = class {
53
- constructor(metadata, rawInput, scope, appendContextHooks, deps = /* @__PURE__ */ new Map()) {
53
+ constructor(metadata, rawInput, scope, appendContextHooks, deps = /* @__PURE__ */ new Map(), retargetEntryHooks) {
54
54
  this.metadata = metadata;
55
55
  this.rawInput = rawInput;
56
56
  this.scope = scope;
57
57
  this.appendContextHooks = appendContextHooks;
58
58
  this.deps = deps;
59
+ this.retargetEntryHooks = retargetEntryHooks;
59
60
  this.input = metadata.inputSchema?.parse?.(rawInput);
60
61
  this.scopeLogger = scope.logger;
61
62
  }
@@ -64,6 +65,7 @@ var FlowBase = class {
64
65
  scope;
65
66
  appendContextHooks;
66
67
  deps;
68
+ retargetEntryHooks;
67
69
  /**
68
70
  * The id of the app that owns the entry a run targets, read from the raw input before hooks load.
69
71
  * Entries an app's adapters and plugins provide belong to that app. App-scoped hooks run only when it matches their app.
@@ -118,6 +120,10 @@ var FlowBase = class {
118
120
  set error(value) {
119
121
  shadowWithOwnValue(this, "error", value);
120
122
  }
123
+ /** Hand the stages still to come to the app and `static` hooks of the entry a hook switched to, in place of the first's. */
124
+ async useEntryHooks(ownerId, entryClass) {
125
+ await this.retargetEntryHooks?.(ownerId, entryClass);
126
+ }
121
127
  respond(output) {
122
128
  throw FlowControl.respond(this.metadata.outputSchema.parse(output));
123
129
  }
@@ -13,7 +13,8 @@ var sessionIdSchema = z.object({
13
13
  var authorizationSchema = z.object({
14
14
  token: z.string(),
15
15
  session: sessionIdSchema.optional(),
16
- user: userClaimSchema
16
+ user: userClaimSchema,
17
+ principalIssuer: z.string().optional()
17
18
  });
18
19
  export {
19
20
  aiPlatformTypeSchema,
@@ -7,7 +7,7 @@ function sessionIdPresentedBy(request) {
7
7
  return typeof query === "string" && query.length > 0 ? query : void 0;
8
8
  }
9
9
  function authInfoFromAuthorization(authorization, presentedSessionId) {
10
- const { token, user, session } = authorization;
10
+ const { token, user, session, principalIssuer } = authorization;
11
11
  const verifiedSession = session !== void 0 && presentedSessionId !== void 0 && session.id === presentedSessionId ? session : void 0;
12
12
  return {
13
13
  token,
@@ -18,7 +18,8 @@ function authInfoFromAuthorization(authorization, presentedSessionId) {
18
18
  extra: {
19
19
  user,
20
20
  sessionId: verifiedSession?.id,
21
- sessionPayload: verifiedSession?.payload
21
+ sessionPayload: verifiedSession?.payload,
22
+ principalIssuer
22
23
  }
23
24
  };
24
25
  }
@@ -20,7 +20,7 @@ import {
20
20
  withHookTrace
21
21
  } from "../hooks/hook-observers.mjs";
22
22
  import { hookOwnerName } from "../hooks/hook-order.mjs";
23
- import { bindContextHookTargets, staticHooksFor } from "../hooks/hooks.utils.mjs";
23
+ import { bindContextHookTargets, sourceMetadataOf, staticHooksFor } from "../hooks/hooks.utils.mjs";
24
24
  import { writeHttpResponse } from "../server/server.validation.mjs";
25
25
  import { flowErrorToHttpOutput } from "../transport/flow-error-output.mjs";
26
26
  import { deferredFlowLoader } from "./deferred-flow.mjs";
@@ -33,6 +33,7 @@ import {
33
33
  } from "./flow.stages.mjs";
34
34
  import { collectFlowMetadata } from "./flow.utils.mjs";
35
35
  var FAILED_OUTCOMES = /* @__PURE__ */ new Set(["fail", "abort", "unknown_error"]);
36
+ var REGISTRY_HOOK_ORDER_START = -1e6;
36
37
  var CAP = (s) => s ? s[0].toUpperCase() + s.slice(1) : s;
37
38
  var stageKeysByName = /* @__PURE__ */ new Map();
38
39
  function stageKeysOf(stage) {
@@ -377,9 +378,12 @@ var FlowInstance = class extends FlowEntry {
377
378
  const hookOwnerId = await FlowClass.resolveHookOwnerId?.(input, scope);
378
379
  const entryClass = await FlowClass.resolveHookEntryClass?.(input, scope);
379
380
  const entryStaticHooks = entryClass ? staticHooksFor(this.hooks.getClsHooks(entryClass), name) : [];
381
+ const bindRun = { sessionKey, contextProviders: mergedDeps, contextSource: this.globalProviders };
382
+ const ownerHooks = this.hooks.getFlowHooksForOwner(name, hookOwnerId) ?? [];
383
+ let registryHookOrder = REGISTRY_HOOK_ORDER_START + ownerHooks.length;
380
384
  const initialInjectedHooks = await bindContextHookTargets(
381
- this.hooks.getFlowHooksForOwner(name, hookOwnerId) ?? [],
382
- { sessionKey, contextProviders: mergedDeps, contextSource: this.globalProviders }
385
+ ownerHooks,
386
+ bindRun
383
387
  );
384
388
  let contextReady = false;
385
389
  const trace = this.tracesHooks ? [] : void 0;
@@ -426,9 +430,43 @@ var FlowInstance = class extends FlowEntry {
426
430
  const appendContextHooks = async (hooks) => {
427
431
  await materializeAndMerge(hooks);
428
432
  };
429
- const context = new FlowClass(this.metadata, input, scope, appendContextHooks, mergedDeps);
433
+ let entryHooks = [...ownerHooks, ...entryStaticHooks];
434
+ let entryTarget = { ownerId: hookOwnerId, entryClass };
435
+ const retargetEntryHooks = async (ownerId, nextEntryClass) => {
436
+ if (ownerId === entryTarget.ownerId && nextEntryClass === entryTarget.entryClass) return;
437
+ entryTarget = { ownerId, entryClass: nextEntryClass };
438
+ const nextStaticHooks = nextEntryClass ? staticHooksFor(this.hooks.getClsHooks(nextEntryClass), name) : [];
439
+ const nextOwnerHooks = this.hooks.getFlowHooksForOwner(name, ownerId) ?? [];
440
+ const nextHooks = [...nextOwnerHooks, ...nextStaticHooks];
441
+ const leaving = new Set(entryHooks.filter((hook) => !nextHooks.includes(hook)).map((hook) => hook.metadata));
442
+ const joining = nextHooks.filter((hook) => !entryHooks.includes(hook));
443
+ entryHooks = nextHooks;
444
+ if (leaving.size > 0) {
445
+ if (!ownsStages) {
446
+ stages = cloneStageMap(baseStages);
447
+ ownsStages = true;
448
+ }
449
+ for (const key of Object.keys(stages)) {
450
+ stages[key] = stages[key].filter((entry) => !leaving.has(sourceMetadataOf(entry.hook)));
451
+ }
452
+ }
453
+ const joiningOwnerHooks = joining.filter((hook) => nextOwnerHooks.includes(hook));
454
+ await materializeAndMerge(await bindContextHookTargets(joiningOwnerHooks, bindRun), {
455
+ orderStart: registryHookOrder
456
+ });
457
+ registryHookOrder += joiningOwnerHooks.length;
458
+ await materializeAndMerge(joining.filter((hook) => !nextOwnerHooks.includes(hook)));
459
+ };
460
+ const context = new FlowClass(
461
+ this.metadata,
462
+ input,
463
+ scope,
464
+ appendContextHooks,
465
+ mergedDeps,
466
+ retargetEntryHooks
467
+ );
430
468
  contextReady = true;
431
- await materializeAndMerge(initialInjectedHooks, { orderStart: -1e6 });
469
+ await materializeAndMerge(initialInjectedHooks, { orderStart: REGISTRY_HOOK_ORDER_START });
432
470
  if (ownsStages) orderBase = nextStageOrder(stages);
433
471
  await materializeAndMerge(entryStaticHooks);
434
472
  if (this.loggedHookOrders) this.logHookOrderOnce(this.loggedHookOrders, stages, hookOwnerId, entryClass);
@@ -56,6 +56,10 @@ function contextInstanceOf(providers, token) {
56
56
  return typeof instance === "object" && instance !== null ? instance : void 0;
57
57
  };
58
58
  }
59
+ var boundFrom = /* @__PURE__ */ new WeakMap();
60
+ function sourceMetadataOf(metadata) {
61
+ return boundFrom.get(metadata) ?? metadata;
62
+ }
59
63
  async function bindContextHookTargets(hooks, run) {
60
64
  if (!hooks.some((hook) => hook.metadata.contextTarget)) return [...hooks];
61
65
  const bound = [];
@@ -66,10 +70,11 @@ async function bindContextHookTargets(hooks, run) {
66
70
  continue;
67
71
  }
68
72
  const target = await contextTarget(run);
69
- if (target)
70
- bound.push({
71
- metadata: { ...hook.metadata, target, contextTarget: void 0 }
72
- });
73
+ if (target) {
74
+ const metadata = { ...hook.metadata, target, contextTarget: void 0 };
75
+ boundFrom.set(metadata, hook.metadata);
76
+ bound.push({ metadata });
77
+ }
73
78
  }
74
79
  return bound;
75
80
  }
@@ -87,5 +92,6 @@ export {
87
92
  normalizeHooksFromCls,
88
93
  normalizeHooksFromProviders,
89
94
  serverProviderHooks,
95
+ sourceMetadataOf,
90
96
  staticHooksFor
91
97
  };