@burdenoff/be-sdk 2026.1123.2 → 2026.1123.4

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 (71) hide show
  1. package/dist/auth/index.d.ts +1 -1
  2. package/dist/auth/index.js +1 -1
  3. package/dist/{auth-C5ctwSLp.js → auth-DqD4_tHM.js} +39 -6
  4. package/dist/auth-DqD4_tHM.js.map +1 -0
  5. package/dist/{client-BgAEvDC2.d.ts → client-NknQrWsP.d.ts} +3 -1
  6. package/dist/feature-flags/index.d.ts +1 -1
  7. package/dist/graph/index.d.ts +1 -1
  8. package/dist/graph/index.js +2 -2
  9. package/dist/{graph-Egewc_K7.js → graph-BdoM7_90.js} +2 -2
  10. package/dist/{graph-Egewc_K7.js.map → graph-BdoM7_90.js.map} +1 -1
  11. package/dist/{index-HeUeEsMU.d.ts → index-BaskMO3C.d.ts} +8 -2
  12. package/dist/{index-479i3w77.d.ts → index-BgOU0pxB.d.ts} +30 -5
  13. package/dist/{index-FKohsiex.d.ts → index-BrRQe24P.d.ts} +3 -2
  14. package/dist/{index-BiTzGUZP.d.ts → index-BwgBHUuX.d.ts} +2 -2
  15. package/dist/{index-DMeQh75K.d.ts → index-CIayzveI.d.ts} +1 -1
  16. package/dist/{index-DSA8h4W3.d.ts → index-CUiL43SY.d.ts} +2 -2
  17. package/dist/{index-CzMD97-N.d.ts → index-CkQieKSy.d.ts} +16 -2
  18. package/dist/{index-nP7g1FZm.d.ts → index-DFEKBKBE.d.ts} +4 -1
  19. package/dist/{index-DhFP_AIB.d.ts → index-DkitHCtV.d.ts} +1 -1
  20. package/dist/index.d.ts +8 -8
  21. package/dist/index.js +7 -7
  22. package/dist/init/index.js +1 -1
  23. package/dist/{init-BCLZQ1Gz.js → init-4vv4gYEm.js} +2 -2
  24. package/dist/{init-BCLZQ1Gz.js.map → init-4vv4gYEm.js.map} +1 -1
  25. package/dist/instrumentation/index.d.ts +2 -2
  26. package/dist/instrumentation/index.js +3 -3
  27. package/dist/{instrumentation-xkkmDgJ0.js → instrumentation-C738xDj8.js} +45 -6
  28. package/dist/instrumentation-C738xDj8.js.map +1 -0
  29. package/dist/lake/index.d.ts +52 -3
  30. package/dist/lake/index.js +238 -9
  31. package/dist/lake/index.js.map +1 -1
  32. package/dist/metrics/index.js +1 -1
  33. package/dist/{metrics-BrLwNUrb.js → metrics-CQaHT12m.js} +2 -2
  34. package/dist/{metrics-BrLwNUrb.js.map → metrics-CQaHT12m.js.map} +1 -1
  35. package/dist/{metrics-collector-C2eShrlW.js → metrics-collector-DXQrMUle.js} +216 -139
  36. package/dist/metrics-collector-DXQrMUle.js.map +1 -0
  37. package/dist/{middleware-B9eyLP7A.js → middleware-z8KzMFU_.js} +95 -5
  38. package/dist/middleware-z8KzMFU_.js.map +1 -0
  39. package/dist/prisma/index.d.ts +3 -3
  40. package/dist/prisma/index.js +3 -3
  41. package/dist/{prisma-CML_Prrn.js → prisma-J-ZUmVWJ.js} +4 -2
  42. package/dist/{prisma-CML_Prrn.js.map → prisma-J-ZUmVWJ.js.map} +1 -1
  43. package/dist/{rate-limit-CBrK_U5H.js → rate-limit-ISSpByjW.js} +25 -25
  44. package/dist/rate-limit-ISSpByjW.js.map +1 -0
  45. package/dist/resource-caps/index.d.ts +77 -0
  46. package/dist/resource-caps/index.js +235 -31
  47. package/dist/resource-caps/index.js.map +1 -1
  48. package/dist/security/index.d.ts +1 -1
  49. package/dist/security/index.js +1 -1
  50. package/dist/security/rate-limit/index.d.ts +1 -1
  51. package/dist/security/rate-limit/index.js +1 -1
  52. package/dist/server/index.d.ts +4 -4
  53. package/dist/server/index.js +112 -6
  54. package/dist/server/index.js.map +1 -1
  55. package/dist/tags/index.d.ts +1 -1
  56. package/dist/tags/index.js +1 -1
  57. package/dist/{tags-CbijgoqR.js → tags-C316oA9r.js} +14 -3
  58. package/dist/{tags-CbijgoqR.js.map → tags-C316oA9r.js.map} +1 -1
  59. package/dist/telemetry/index.d.ts +1 -1
  60. package/dist/telemetry/index.js +1 -1
  61. package/dist/{types-De_pO1Wz.d.ts → types-BWN8tMdF.d.ts} +5 -1
  62. package/dist/utils/index.d.ts +2 -2
  63. package/dist/utils/index.js +2 -2
  64. package/dist/{utils-DL85Tnbn.js → utils-DpW6K_iB.js} +24 -7
  65. package/dist/{utils-DL85Tnbn.js.map → utils-DpW6K_iB.js.map} +1 -1
  66. package/package.json +1 -1
  67. package/dist/auth-C5ctwSLp.js.map +0 -1
  68. package/dist/instrumentation-xkkmDgJ0.js.map +0 -1
  69. package/dist/metrics-collector-C2eShrlW.js.map +0 -1
  70. package/dist/middleware-B9eyLP7A.js.map +0 -1
  71. package/dist/rate-limit-CBrK_U5H.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import { A as EntityTagInfo, B as TagVocabularyRef, C as ENTITY_TAGS_GRAPHQL_CODES, D as AvailableTag, E as isEntityTagsError, F as TagActor, H as TagsGatewayClient, I as TagActorType, L as TagAssignmentSource, M as RawTagAssignment, N as TAG_ACTOR_TYPES, O as CreateTagOptions, P as TAG_ASSIGNMENT_SOURCES, R as TagEntityOptions, S as entityTagsTypeNames, T as EntityTagsErrorCode, V as TaggedEntityPage, _ as slugifyTagKey, a as EntityTagMutationEvent, b as assertTagPrefix, c as createEntityTagResolvers, d as EntityTagsSdlOptions, f as UNIVERSAL_TAG_STUB_SDL, g as mapTagAssignment, h as TagsGatewayAdapterOptions, i as EntityTagBinding, j as FindEntitiesByTagsOptions, k as EntityTagAssignment, l as defaultTagActor, m as TagsGatewayAdapter, n as CreateEntityTagResolversOptions, o as EntityTagOperation, p as buildEntityTagsSdl, r as EntityTagAccessCheck, s as EntityTagResolvers, u as EntityTagsRbacOptions, v as EntityTagsFieldNames, w as EntityTagsError, x as entityTagsFieldNames, y as EntityTagsTypeNames, z as TagVocabularyConfig } from "../index-HeUeEsMU.js";
1
+ import { A as EntityTagInfo, B as TagVocabularyRef, C as ENTITY_TAGS_GRAPHQL_CODES, D as AvailableTag, E as isEntityTagsError, F as TagActor, H as TagsGatewayClient, I as TagActorType, L as TagAssignmentSource, M as RawTagAssignment, N as TAG_ACTOR_TYPES, O as CreateTagOptions, P as TAG_ASSIGNMENT_SOURCES, R as TagEntityOptions, S as entityTagsTypeNames, T as EntityTagsErrorCode, V as TaggedEntityPage, _ as slugifyTagKey, a as EntityTagMutationEvent, b as assertTagPrefix, c as createEntityTagResolvers, d as EntityTagsSdlOptions, f as UNIVERSAL_TAG_STUB_SDL, g as mapTagAssignment, h as TagsGatewayAdapterOptions, i as EntityTagBinding, j as FindEntitiesByTagsOptions, k as EntityTagAssignment, l as defaultTagActor, m as TagsGatewayAdapter, n as CreateEntityTagResolversOptions, o as EntityTagOperation, p as buildEntityTagsSdl, r as EntityTagAccessCheck, s as EntityTagResolvers, u as EntityTagsRbacOptions, v as EntityTagsFieldNames, w as EntityTagsError, x as entityTagsFieldNames, y as EntityTagsTypeNames, z as TagVocabularyConfig } from "../index-BaskMO3C.js";
2
2
  export { type AvailableTag, type CreateEntityTagResolversOptions, type CreateTagOptions, ENTITY_TAGS_GRAPHQL_CODES, type EntityTagAccessCheck, type EntityTagAssignment, type EntityTagBinding, type EntityTagInfo, type EntityTagMutationEvent, type EntityTagOperation, type EntityTagResolvers, EntityTagsError, type EntityTagsErrorCode, type EntityTagsFieldNames, type EntityTagsRbacOptions, type EntityTagsSdlOptions, type EntityTagsTypeNames, type FindEntitiesByTagsOptions, type RawTagAssignment, TAG_ACTOR_TYPES, TAG_ASSIGNMENT_SOURCES, type TagActor, type TagActorType, type TagAssignmentSource, type TagEntityOptions, type TagVocabularyConfig, type TagVocabularyRef, type TaggedEntityPage, TagsGatewayAdapter, type TagsGatewayAdapterOptions, type TagsGatewayClient, UNIVERSAL_TAG_STUB_SDL, assertTagPrefix, buildEntityTagsSdl, createEntityTagResolvers, defaultTagActor, entityTagsFieldNames, entityTagsTypeNames, isEntityTagsError, mapTagAssignment, slugifyTagKey };
@@ -1,4 +1,4 @@
1
- import { a as buildEntityTagsSdl, c as slugifyTagKey, d as entityTagsTypeNames, f as ENTITY_TAGS_GRAPHQL_CODES, g as TAG_ASSIGNMENT_SOURCES, h as TAG_ACTOR_TYPES, i as UNIVERSAL_TAG_STUB_SDL, l as assertTagPrefix, m as isEntityTagsError, n as createEntityTagResolvers, o as TagsGatewayAdapter, p as EntityTagsError, r as defaultTagActor, s as mapTagAssignment, u as entityTagsFieldNames } from "../tags-CbijgoqR.js";
1
+ import { a as buildEntityTagsSdl, c as slugifyTagKey, d as entityTagsTypeNames, f as ENTITY_TAGS_GRAPHQL_CODES, g as TAG_ASSIGNMENT_SOURCES, h as TAG_ACTOR_TYPES, i as UNIVERSAL_TAG_STUB_SDL, l as assertTagPrefix, m as isEntityTagsError, n as createEntityTagResolvers, o as TagsGatewayAdapter, p as EntityTagsError, r as defaultTagActor, s as mapTagAssignment, u as entityTagsFieldNames } from "../tags-C316oA9r.js";
2
2
 
3
3
  export { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, TAG_ACTOR_TYPES, TAG_ASSIGNMENT_SOURCES, TagsGatewayAdapter, UNIVERSAL_TAG_STUB_SDL, assertTagPrefix, buildEntityTagsSdl, createEntityTagResolvers, defaultTagActor, entityTagsFieldNames, entityTagsTypeNames, isEntityTagsError, mapTagAssignment, slugifyTagKey };
4
4
  //# sourceMappingURL=index.js.map
@@ -647,6 +647,7 @@ type ${types.taggedEntityPage} {
647
647
  *
648
648
  * @example
649
649
  * ```ts
650
+ * import { GraphQLError } from 'graphql';
650
651
  * import { buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';
651
652
  *
652
653
  * const { Query, Mutation, types } = createEntityTagResolvers({
@@ -656,6 +657,12 @@ type ${types.taggedEntityPage} {
656
657
  * WorkflowDefinition: { entityType: 'FLUIDGRIDS_WORKFLOW', entityId: (p) => String(p.workflowKey ?? '') },
657
658
  * WorkflowRun: { entityType: 'FLUIDGRIDS_RUN' },
658
659
  * },
660
+ * authorizeEntity: async ({ entityType, entityId, actor }, ctx) => {
661
+ * const owned = await entityExistsForActor(ctx.prisma, entityType, entityId, actor);
662
+ * if (!owned) {
663
+ * throw new GraphQLError('Not found', { extensions: { code: 'NOT_FOUND' } });
664
+ * }
665
+ * },
659
666
  * mapError: (error, ctx) => workflowError(`tags.errors.${error.code}`, error.graphqlCode, ctx, error.details),
660
667
  * });
661
668
  * ```
@@ -694,10 +701,14 @@ function defaultMapError(error) {
694
701
  } });
695
702
  }
696
703
  function createEntityTagResolvers(options) {
697
- const { adapter } = options;
698
- const fields = entityTagsFieldNames(options.prefix);
704
+ const { adapter, prefix } = options;
705
+ const fields = entityTagsFieldNames(prefix);
699
706
  const getActor = options.getActor ?? ((context) => defaultTagActor(context));
700
707
  const mapError = options.mapError ?? ((error) => defaultMapError(error));
708
+ if (typeof options.authorizeEntity !== "function") {
709
+ if (options.unsafeAllowUncheckedEntityIds === true) logger.warn("[be-sdk/tags] createEntityTagResolvers initialized with unsafeAllowUncheckedEntityIds=true — entity-addressed tag resolvers will NOT verify entity existence or object-level authorization", { prefix });
710
+ else throw new EntityTagsError("CONFIGURATION_ERROR", "authorizeEntity is required in createEntityTagResolvers (pass unsafeAllowUncheckedEntityIds: true only if entity IDs are intentionally unchecked)", { prefix });
711
+ }
701
712
  for (const [typeName, binding] of Object.entries(options.entities ?? {})) if (!adapter.isValidEntityType(binding.entityType)) throw new EntityTagsError("CONFIGURATION_ERROR", `${typeName} is bound to entity type "${binding.entityType}", which the adapter does not register`, {
702
713
  typeName,
703
714
  entityType: binding.entityType
@@ -865,4 +876,4 @@ var tags_exports = /* @__PURE__ */ __exportAll({
865
876
  });
866
877
 
867
878
  export { buildEntityTagsSdl as a, slugifyTagKey as c, entityTagsTypeNames as d, ENTITY_TAGS_GRAPHQL_CODES as f, TAG_ASSIGNMENT_SOURCES as g, TAG_ACTOR_TYPES as h, UNIVERSAL_TAG_STUB_SDL as i, assertTagPrefix as l, isEntityTagsError as m, createEntityTagResolvers as n, TagsGatewayAdapter as o, EntityTagsError as p, defaultTagActor as r, mapTagAssignment as s, tags_exports as t, entityTagsFieldNames as u };
868
- //# sourceMappingURL=tags-CbijgoqR.js.map
879
+ //# sourceMappingURL=tags-C316oA9r.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tags-CbijgoqR.js","names":[],"sources":["../src/tags/types.ts","../src/tags/errors.ts","../src/tags/naming.ts","../src/tags/adapter.ts","../src/tags/sdl.ts","../src/tags/resolvers.ts","../src/tags/index.ts"],"sourcesContent":["/**\n * Entity tags — shared types.\n *\n * Every product service that lets users tag its own entities talks to the one\n * polymorphic tag owner, **wspace-tags-svc**, through the internal workspace\n * gateway. These types describe both the tags-svc wire shape and the\n * projection the service publishes in its own subgraph.\n */\nimport type { GraphQLRequestOptions, GraphQLResponse } from '../gateway/types.js';\n\n/** Actor types the gateway forwards in `x-actor-type`. */\nexport const TAG_ACTOR_TYPES = ['user', 'app', 'service', 'super_admin'] as const;\n\nexport type TagActorType = (typeof TAG_ACTOR_TYPES)[number];\n\n/** The caller a tag operation runs on behalf of (forwarded as `x-actor-*` / `x-workspace-id`). */\nexport interface TagActor {\n /** `x-actor-id` — the user/app/service id the gateway authenticated. */\n actorId: string;\n /** `x-workspace-id` — tags-svc scopes every vocabulary, tag and assignment by it. */\n workspaceId: string;\n /** `x-actor-type`; defaults to `user`. */\n actorType?: TagActorType;\n}\n\n/** `AssignmentSource` enum members accepted by wspace-tags-svc. */\nexport const TAG_ASSIGNMENT_SOURCES = ['AUTOMATIC', 'COMPUTED', 'IMPORTED', 'INHERITED', 'MANUAL', 'MIGRATED'] as const;\n\nexport type TagAssignmentSource = (typeof TAG_ASSIGNMENT_SOURCES)[number];\n\n/** `UniversalTagAssignment` as it comes back over the wire from wspace-tags-svc. */\nexport interface RawTagAssignment {\n id: string;\n tagId: string;\n entityType: string;\n entityId: string;\n source: string;\n assignedById?: string | null;\n createdAt?: string | null;\n validFrom?: string | null;\n validTo?: string | null;\n metadata?: unknown;\n tag?: { id: string; key?: string | null; label?: string | null; color?: string | null } | null;\n}\n\n/** Inline (non-federated) tag projection so clients render labels in one round-trip. */\nexport interface EntityTagInfo {\n id: string;\n key: string | null;\n label: string | null;\n color: string | null;\n}\n\n/** A tag assigned to one of the service's entities, in the shape its subgraph publishes. */\nexport interface EntityTagAssignment {\n id: string;\n tagId: string;\n /** Federated `UniversalTag` reference — only `id` resolves locally; tags-svc owns the rest. */\n tag: { id: string } | null;\n tagInfo: EntityTagInfo | null;\n entityType: string;\n entityId: string;\n source: string;\n assignedBy: string | null;\n assignedAt: Date | null;\n validFrom: Date | null;\n validTo: Date | null;\n metadata: unknown;\n}\n\n/** An assignable workspace tag. */\nexport interface AvailableTag {\n id: string;\n key: string;\n label: string;\n color: string | null;\n}\n\n/** Minimal vocabulary reference returned by tags-svc. */\nexport interface TagVocabularyRef {\n id: string;\n key: string;\n name: string;\n}\n\n/** The workspace-scoped vocabulary that inline-created tags land in. */\nexport interface TagVocabularyConfig {\n /** Stable vocabulary key, e.g. `fluidgrids-tags`. Looked up first, created when missing. */\n key: string;\n /** Display name used when the vocabulary has to be created. */\n name: string;\n description?: string;\n /**\n * A pinned vocabulary id. Used when it exists in the caller's workspace; ignored\n * (falls back to `key`) when it does not, so one id never leaks across workspaces.\n */\n id?: string;\n}\n\n/** Options for {@link TagsGatewayAdapter.tagEntity}. */\nexport interface TagEntityOptions {\n tagId: string;\n source?: string | null;\n validFrom?: Date | null;\n validTo?: Date | null;\n metadata?: Record<string, unknown> | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.createTag}. */\nexport interface CreateTagOptions {\n label: string;\n color?: string | null;\n /**\n * Target vocabulary. `undefined`/`null` resolves (or creates) the adapter's default\n * vocabulary. Any explicit value, even an empty string, is sent as-is so an unknown id\n * surfaces as a tags-svc error instead of silently misfiling the tag.\n */\n vocabularyId?: string | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.findEntityIdsByTags}. */\nexport interface FindEntitiesByTagsOptions {\n /** `true` = entity must carry every tag; `false` (default) = any of them. */\n matchAll?: boolean;\n /** Clamped to 1..200; default 50. */\n limit?: number | null;\n cursor?: string | null;\n}\n\n/** One page of entity ids carrying the requested tags. */\nexport interface TaggedEntityPage {\n entityIds: string[];\n total: number;\n hasMore: boolean;\n nextCursor: string | null;\n}\n\n/** The slice of the be-sdk `GatewayClient` the adapter needs (lets tests pass a fake). */\nexport interface TagsGatewayClient {\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n}\n","/**\n * Entity tags — error type.\n *\n * Services map {@link EntityTagsError} onto their own i18n GraphQL errors (see the\n * `invalidEntityTypeError` / `mapError` hooks of `createEntityTagResolvers`); the\n * `code` is stable so that mapping never has to parse messages.\n */\n\nexport type EntityTagsErrorCode =\n /** `entityType` is not one the service registered as taggable. */\n | 'INVALID_ENTITY_TYPE'\n /** `source` is not a tags-svc `AssignmentSource`. */\n | 'INVALID_SOURCE'\n /** A required argument (entity id, tag id, label, …) is empty. */\n | 'INVALID_INPUT'\n /** No actor/workspace on the request — tags are always workspace-scoped. */\n | 'MISSING_CONTEXT'\n /** tags-svc answered without the expected payload. */\n | 'UPSTREAM_ERROR'\n /** The adapter / resolver factory was configured inconsistently (thrown at boot). */\n | 'CONFIGURATION_ERROR';\n\n/** GraphQL `extensions.code` each {@link EntityTagsErrorCode} should surface as. */\nexport const ENTITY_TAGS_GRAPHQL_CODES: Record<EntityTagsErrorCode, string> = {\n INVALID_ENTITY_TYPE: 'BAD_USER_INPUT',\n INVALID_SOURCE: 'BAD_USER_INPUT',\n INVALID_INPUT: 'BAD_USER_INPUT',\n MISSING_CONTEXT: 'UNAUTHENTICATED',\n UPSTREAM_ERROR: 'INTERNAL_SERVER_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_SERVER_ERROR',\n};\n\nexport class EntityTagsError extends Error {\n readonly code: EntityTagsErrorCode;\n readonly details: Record<string, unknown>;\n\n constructor(code: EntityTagsErrorCode, message: string, details: Record<string, unknown> = {}) {\n super(message);\n this.name = 'EntityTagsError';\n this.code = code;\n this.details = details;\n }\n\n /** The GraphQL `extensions.code` this error maps to. */\n get graphqlCode(): string {\n return ENTITY_TAGS_GRAPHQL_CODES[this.code];\n }\n}\n\nexport function isEntityTagsError(error: unknown): error is EntityTagsError {\n return error instanceof EntityTagsError;\n}\n","/**\n * Entity tags — GraphQL naming.\n *\n * Every service in the workspaces supergraph publishes its own tag surface, so\n * every type and root field must be unique to the service: unprefixed\n * `EntityTagAssignment` / `AvailableTag` / `EntityTagInfo` declared by two\n * subgraphs are non-shareable value types and break composition. The SDL\n * builder and the resolver factory both derive their names from here, so a\n * service's schema and its resolver map can never drift apart.\n */\nimport { EntityTagsError } from './errors.js';\n\nconst PREFIX_PATTERN = /^[A-Z][A-Za-z0-9]*$/;\n\n/** Root field names, derived from the service prefix (`Fluidgrids` → `fluidgridsEntityTags`, …). */\nexport interface EntityTagsFieldNames {\n entityTags: string;\n searchTags: string;\n availableTags: string;\n entitiesByTags: string;\n tagEntity: string;\n untagEntity: string;\n replaceEntityTags: string;\n createTag: string;\n}\n\n/** Type / input names the tag surface declares. */\nexport interface EntityTagsTypeNames {\n getEntityTagsInput: string;\n tagEntityInput: string;\n untagEntityInput: string;\n replaceEntityTagsInput: string;\n createTagInput: string;\n entitiesByTagsInput: string;\n tagInfo: string;\n tagAssignment: string;\n availableTag: string;\n taggedEntityPage: string;\n}\n\nexport function assertTagPrefix(prefix: string): void {\n if (!PREFIX_PATTERN.test(prefix)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags prefix must be PascalCase ([A-Z][A-Za-z0-9]*), got \"${prefix}\"`,\n { prefix }\n );\n }\n}\n\nfunction lowerFirst(value: string): string {\n return value.charAt(0).toLowerCase() + value.slice(1);\n}\n\nexport function entityTagsFieldNames(prefix: string): EntityTagsFieldNames {\n assertTagPrefix(prefix);\n const camel = lowerFirst(prefix);\n return {\n entityTags: `${camel}EntityTags`,\n searchTags: `search${prefix}Tags`,\n availableTags: `available${prefix}Tags`,\n entitiesByTags: `${camel}EntitiesByTags`,\n tagEntity: `tag${prefix}Entity`,\n untagEntity: `untag${prefix}Entity`,\n replaceEntityTags: `replace${prefix}EntityTags`,\n createTag: `create${prefix}Tag`,\n };\n}\n\n/**\n * Type names for `prefix`. Defaults carry the prefix everywhere (the FluidGrids\n * convention). `overrides` exists for services that already published legacy\n * names (VibeControls ships `EntityTagAssignment`, `TagEntityInput`, …) and must\n * keep them for existing clients' fragments.\n */\nexport function entityTagsTypeNames(prefix: string, overrides: Partial<EntityTagsTypeNames> = {}): EntityTagsTypeNames {\n assertTagPrefix(prefix);\n const names: EntityTagsTypeNames = {\n getEntityTagsInput: `Get${prefix}EntityTagsInput`,\n tagEntityInput: `Tag${prefix}EntityInput`,\n untagEntityInput: `Untag${prefix}EntityInput`,\n replaceEntityTagsInput: `Replace${prefix}EntityTagsInput`,\n createTagInput: `Create${prefix}TagInput`,\n entitiesByTagsInput: `${prefix}EntitiesByTagsInput`,\n tagInfo: `${prefix}TagInfo`,\n tagAssignment: `${prefix}TagAssignment`,\n availableTag: `${prefix}AvailableTag`,\n taggedEntityPage: `${prefix}TaggedEntityPage`,\n ...overrides,\n };\n\n const seen = new Map<string, string>();\n for (const [role, name] of Object.entries(names)) {\n if (!PREFIX_PATTERN.test(name)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags type name for ${role} is not a valid type name`, {\n role,\n name,\n });\n }\n const clash = seen.get(name);\n if (clash) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags type name \"${name}\" is used for both ${clash} and ${role}`,\n {\n name,\n }\n );\n }\n seen.set(name, role);\n }\n return names;\n}\n","/**\n * TagsGatewayAdapter — one implementation of \"tag my entities\" for every service.\n *\n * Thirteen services carried their own copy of this adapter (VibeControls,\n * FluidGrids, BigConsole, files, integrations, …) and the copies drifted:\n * argument order (`userId, workspaceId` vs `workspaceId, userId`), a hard-coded\n * `x-actor-type: user`, `response.data!` non-null assertions, no source\n * validation. This class is the lifted, configurable version: a service\n * supplies its taggable entity types, its default vocabulary and (optionally)\n * the gateway client, and gets the full tag surface.\n *\n * All calls are same-layer M2M to wspace-tags-svc through the internal\n * workspace gateway (`GatewayClient.internalQuery`, which signs the service JWT);\n * the caller's actor and workspace are forwarded explicitly because tags-svc\n * scopes every vocabulary, tag and assignment by `x-workspace-id`.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter } from '@burdenoff/be-sdk/tags';\n *\n * export const entityTags = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN', 'FLUIDGRIDS_DATATABLE'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n *\n * await entityTags.tagEntity('FLUIDGRIDS_RUN', run.id, { tagId }, { actorId, workspaceId });\n * ```\n */\nimport { EntityTagsError } from './errors.js';\nimport type {\n AvailableTag,\n CreateTagOptions,\n EntityTagAssignment,\n FindEntitiesByTagsOptions,\n RawTagAssignment,\n TagActor,\n TagAssignmentSource,\n TagEntityOptions,\n TagsGatewayClient,\n TaggedEntityPage,\n TagVocabularyConfig,\n TagVocabularyRef,\n} from './types.js';\nimport { TAG_ASSIGNMENT_SOURCES } from './types.js';\n\n/** tags-svc caps; requests outside are clamped rather than rejected. */\nconst SEARCH_LIMIT = { default: 20, max: 100 };\nconst AVAILABLE_LIMIT = { default: 50, max: 200 };\nconst ENTITIES_BY_TAGS_LIMIT = { default: 50, max: 200 };\n\n/** Same-layer tag calls should fail fast; the GatewayClient default is 30s. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\n\nconst ENTITY_TYPE_PATTERN = /^[A-Z][A-Z0-9_]*$/;\n\nconst ASSIGNMENT_FIELDS =\n 'id tagId entityType entityId source assignedById createdAt validFrom validTo metadata tag { id key label color }';\n\nexport interface TagsGatewayAdapterOptions {\n /**\n * The entity types this service owns, e.g. `['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN']`.\n * UPPER_SNAKE_CASE and namespaced by product so two services never share a type.\n */\n entityTypes: readonly string[];\n /** Default vocabulary that inline-created tags (no `vocabularyId`) land in. */\n vocabulary: TagVocabularyConfig;\n /** `source` sent when a caller passes none. Default `MANUAL`. */\n defaultSource?: TagAssignmentSource;\n /**\n * Gateway client, or a factory for one. Defaults to a lazily constructed be-sdk\n * `GatewayClient` (`layer: 'wspace'`, `serviceName` below, or the\n * `SERVICE_LAYER`/`SERVICE_NAME` env when `serviceName` is omitted).\n */\n client?: TagsGatewayClient | (() => TagsGatewayClient | Promise<TagsGatewayClient>);\n /** Service name for the default GatewayClient, e.g. `wspace-workflow-svc`. */\n serviceName?: string;\n /** Per-request timeout for tags-svc calls. Default 10s. */\n requestTimeoutMs?: number;\n}\n\nfunction clampLimit(value: number | null | undefined, bounds: { default: number; max: number }): number {\n if (value === null || value === undefined || !Number.isFinite(value)) return bounds.default;\n return Math.min(Math.max(Math.trunc(value), 1), bounds.max);\n}\n\nfunction toDate(value: string | null | undefined): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction requireNonEmpty(value: string | null | undefined, field: string): string {\n const trimmed = typeof value === 'string' ? value.trim() : '';\n if (!trimmed) {\n throw new EntityTagsError('INVALID_INPUT', `${field} is required`, { field });\n }\n return trimmed;\n}\n\n/** FNV-1a, used only to give non-ASCII labels a stable, non-empty key. */\nfunction shortHash(value: string): string {\n let hash = 0x811c9dc5;\n for (const char of value) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(36);\n}\n\n/**\n * Tag key for a label: lowercase ASCII slug (`\"Needs Review!\"` → `needs-review`).\n * Labels with no ASCII letters or digits (`\"日本\"`) get `tag-<hash>` so the key is\n * never empty (tags-svc rejects an empty key) and stays stable for the same label.\n */\nexport function slugifyTagKey(label: string): string {\n const slug = label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return slug || `tag-${shortHash(label.trim())}`;\n}\n\n/** Map a tags-svc `UniversalTagAssignment` onto the published assignment shape. */\nexport function mapTagAssignment(raw: RawTagAssignment): EntityTagAssignment {\n return {\n id: raw.id,\n tagId: raw.tagId,\n entityType: raw.entityType,\n entityId: raw.entityId,\n source: raw.source,\n assignedBy: raw.assignedById ?? null,\n assignedAt: toDate(raw.createdAt) ?? toDate(raw.validFrom),\n validFrom: toDate(raw.validFrom),\n validTo: toDate(raw.validTo),\n metadata: raw.metadata ?? null,\n tag: raw.tag ? { id: raw.tag.id } : null,\n tagInfo: raw.tag\n ? {\n id: raw.tag.id,\n key: raw.tag.key ?? null,\n label: raw.tag.label ?? null,\n color: raw.tag.color ?? null,\n }\n : null,\n };\n}\n\nexport class TagsGatewayAdapter {\n readonly entityTypes: readonly string[];\n readonly vocabulary: Readonly<TagVocabularyConfig>;\n readonly defaultSource: TagAssignmentSource;\n\n private readonly entityTypeSet: ReadonlySet<string>;\n private readonly requestTimeoutMs: number;\n private readonly clientOption: TagsGatewayAdapterOptions['client'];\n private readonly serviceName: string | undefined;\n private clientPromise: Promise<TagsGatewayClient> | null = null;\n\n constructor(options: TagsGatewayAdapterOptions) {\n if (options.entityTypes.length === 0) {\n throw new EntityTagsError('CONFIGURATION_ERROR', 'TagsGatewayAdapter needs at least one entity type');\n }\n for (const entityType of options.entityTypes) {\n if (!ENTITY_TYPE_PATTERN.test(entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity type \"${entityType}\" must be UPPER_SNAKE_CASE (e.g. FLUIDGRIDS_WORKFLOW)`,\n { entityType }\n );\n }\n }\n requireNonEmpty(options.vocabulary.key, 'vocabulary.key');\n requireNonEmpty(options.vocabulary.name, 'vocabulary.name');\n const defaultSource = options.defaultSource ?? 'MANUAL';\n if (!TAG_ASSIGNMENT_SOURCES.includes(defaultSource)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Unknown default tag source \"${defaultSource}\"`);\n }\n\n this.entityTypes = Object.freeze([...new Set(options.entityTypes)]);\n this.entityTypeSet = new Set(this.entityTypes);\n this.vocabulary = Object.freeze({ ...options.vocabulary });\n this.defaultSource = defaultSource;\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.clientOption = options.client;\n this.serviceName = options.serviceName;\n }\n\n // ── Validation ────────────────────────────────────────────────────────\n\n isValidEntityType(entityType: string): boolean {\n return this.entityTypeSet.has(entityType);\n }\n\n assertEntityType(entityType: string): void {\n if (!this.isValidEntityType(entityType)) {\n throw new EntityTagsError('INVALID_ENTITY_TYPE', `Unsupported entity type \"${entityType}\"`, {\n entityType,\n supported: this.entityTypes,\n });\n }\n }\n\n /** Validate a caller-supplied source; empty means the adapter default. */\n resolveSource(source: string | null | undefined): TagAssignmentSource {\n if (source === null || source === undefined || source === '') return this.defaultSource;\n const normalized = source.toUpperCase();\n const match = TAG_ASSIGNMENT_SOURCES.find((candidate) => candidate === normalized);\n if (!match) {\n throw new EntityTagsError('INVALID_SOURCE', `Unknown tag source \"${source}\"`, {\n source,\n supported: TAG_ASSIGNMENT_SOURCES,\n });\n }\n return match;\n }\n\n // ── Assignments ───────────────────────────────────────────────────────\n\n /** Tags currently assigned to an entity. */\n async getEntityTags(entityType: string, entityId: string, actor: TagActor): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const data = await this.request<{ getEntityTags: RawTagAssignment[] | null }>(\n `query GetEntityTags($entityType: String!, $entityId: ID!) {\n getEntityTags(entityType: $entityType, entityId: $entityId) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id },\n actor\n );\n return (data.getEntityTags ?? []).map(mapTagAssignment);\n }\n\n /** Assign one tag to an entity. */\n async tagEntity(\n entityType: string,\n entityId: string,\n options: TagEntityOptions,\n actor: TagActor\n ): Promise<EntityTagAssignment> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const tagId = requireNonEmpty(options.tagId, 'tagId');\n const source = this.resolveSource(options.source);\n const context = this.requireActor(actor);\n\n const data = await this.request<{ assignTag: RawTagAssignment | null }>(\n `mutation AssignTag($input: AssignTagInput!) {\n assignTag(input: $input) { ${ASSIGNMENT_FIELDS} }\n }`,\n {\n input: {\n tagId,\n entityType,\n entityId: id,\n source,\n validFrom: options.validFrom?.toISOString(),\n validTo: options.validTo?.toISOString(),\n metadata: options.metadata ?? undefined,\n context: { workspaceId: context.workspaceId },\n },\n },\n context\n );\n if (!data.assignTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no assignment', { entityType, tagId });\n }\n return mapTagAssignment(data.assignTag);\n }\n\n /**\n * Remove a tag from an entity. Removes every assignment of that tag on the entity\n * (tags-svc allows several with different validity windows). `false` when the tag\n * was not assigned.\n */\n async untagEntity(entityType: string, entityId: string, tagId: string, actor: TagActor): Promise<boolean> {\n const id = requireNonEmpty(tagId, 'tagId');\n const assignments = await this.getEntityTags(entityType, entityId, actor);\n const matches = assignments.filter((assignment) => assignment.tagId === id);\n if (matches.length === 0) return false;\n\n let removed = false;\n for (const assignment of matches) {\n const data = await this.request<{ removeTagAssignment: boolean | null }>(\n `mutation RemoveTagAssignment($id: ID!) { removeTagAssignment(id: $id) }`,\n { id: assignment.id },\n actor\n );\n removed = data.removeTagAssignment === true || removed;\n }\n return removed;\n }\n\n /** Replace the full tag set on an entity (an empty list clears it). */\n async replaceEntityTags(\n entityType: string,\n entityId: string,\n tagIds: readonly string[],\n actor: TagActor\n ): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n const data = await this.request<{ replaceEntityTags: RawTagAssignment[] | null }>(\n `mutation ReplaceEntityTags($entityType: String!, $entityId: ID!, $tagIds: [ID!]!) {\n replaceEntityTags(entityType: $entityType, entityId: $entityId, tagIds: $tagIds) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id, tagIds: uniqueTagIds },\n actor\n );\n return (data.replaceEntityTags ?? []).map(mapTagAssignment);\n }\n\n /**\n * Ids of `entityType` entities carrying the given tags — the server-side half of\n * \"filter this list by tag\". Intersect the ids with the service's own query.\n */\n async findEntityIdsByTags(\n entityType: string,\n tagIds: readonly string[],\n actor: TagActor,\n options: FindEntitiesByTagsOptions = {}\n ): Promise<TaggedEntityPage> {\n this.assertEntityType(entityType);\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n if (uniqueTagIds.length === 0) {\n throw new EntityTagsError('INVALID_INPUT', 'tagIds must contain at least one tag', { field: 'tagIds' });\n }\n const data = await this.request<{\n getEntitiesByTags: {\n entities: Array<{ entityId: string; entityType: string }>;\n total: number;\n hasMore: boolean;\n nextCursor?: string | null;\n } | null;\n }>(\n `query GetEntitiesByTags($tagIds: [ID!]!, $entityType: String, $matchAll: Boolean, $pagination: TagsPaginationInput) {\n getEntitiesByTags(tagIds: $tagIds, entityType: $entityType, matchAll: $matchAll, pagination: $pagination) {\n entities { entityId entityType } total hasMore nextCursor\n }\n }`,\n {\n tagIds: uniqueTagIds,\n entityType,\n matchAll: options.matchAll ?? false,\n pagination: {\n limit: clampLimit(options.limit, ENTITIES_BY_TAGS_LIMIT),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n },\n },\n actor\n );\n const page = data.getEntitiesByTags;\n if (!page) return { entityIds: [], total: 0, hasMore: false, nextCursor: null };\n return {\n // tags-svc already filters by entityType; re-check so a lax upstream never\n // leaks another product's ids into this service's list.\n entityIds: page.entities.filter((entity) => entity.entityType === entityType).map((entity) => entity.entityId),\n total: page.total,\n hasMore: page.hasMore,\n nextCursor: page.nextCursor ?? null,\n };\n }\n\n // ── Workspace tags ────────────────────────────────────────────────────\n\n /** Search assignable tags in the workspace. */\n async searchTags(query: string, actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ searchTags: AvailableTag[] | null }>(\n `query SearchTags($query: String!, $limit: Int) {\n searchTags(query: $query, limit: $limit) { id key label color }\n }`,\n { query: query.trim(), limit: clampLimit(limit, SEARCH_LIMIT) },\n actor\n );\n return data.searchTags ?? [];\n }\n\n /** List assignable tags in the workspace. */\n async getAvailableTags(actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ getTags: { items: AvailableTag[] | null } | null }>(\n `query GetTags($pagination: TagsPaginationInput) {\n getTags(pagination: $pagination) { items { id key label color } }\n }`,\n { pagination: { limit: clampLimit(limit, AVAILABLE_LIMIT) } },\n actor\n );\n return data.getTags?.items ?? [];\n }\n\n /** Create a workspace tag, in the default vocabulary unless `vocabularyId` is given. */\n async createTag(options: CreateTagOptions, actor: TagActor): Promise<AvailableTag> {\n const label = requireNonEmpty(options.label, 'label');\n const vocabularyId =\n options.vocabularyId !== undefined && options.vocabularyId !== null\n ? options.vocabularyId\n : await this.ensureWorkspaceVocabulary(actor);\n\n const data = await this.request<{ createTag: AvailableTag | null }>(\n `mutation CreateTag($input: CreateTagInput!) {\n createTag(input: $input) { id key label color }\n }`,\n {\n input: {\n vocabularyId,\n key: slugifyTagKey(label),\n label,\n color: options.color || undefined,\n },\n },\n actor\n );\n if (!data.createTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no tag', { label });\n }\n return data.createTag;\n }\n\n // ── Vocabularies ──────────────────────────────────────────────────────\n\n /**\n * Resolve the workspace's default vocabulary id, creating the vocabulary on first\n * use. Order: pinned `id` (if it exists in this workspace) → lookup by `key` →\n * create → re-read by key (a concurrent request may have created it first).\n */\n async ensureWorkspaceVocabulary(actor: TagActor, override: Partial<TagVocabularyConfig> = {}): Promise<string> {\n const vocabulary = { ...this.vocabulary, ...override };\n\n if (vocabulary.id) {\n const byId = await this.getVocabularyById(vocabulary.id, actor);\n if (byId?.id) return byId.id;\n }\n\n const byKey = await this.getVocabularyByKey(vocabulary.key, actor);\n if (byKey?.id) return byKey.id;\n\n let createError: unknown = null;\n try {\n const created = await this.createVocabulary(vocabulary, actor);\n if (created?.id) return created.id;\n } catch (error) {\n // Most likely a unique-key race with a concurrent request; the re-read below\n // decides. Kept so the failure is not swallowed when the re-read finds nothing.\n createError = error;\n }\n\n const afterCreate = await this.getVocabularyByKey(vocabulary.key, actor);\n if (afterCreate?.id) return afterCreate.id;\n\n if (createError) throw createError;\n throw new EntityTagsError('UPSTREAM_ERROR', `Failed to resolve tag vocabulary \"${vocabulary.key}\"`, {\n vocabularyKey: vocabulary.key,\n });\n }\n\n async getVocabularyById(id: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabulary: TagVocabularyRef | null }>(\n `query GetVocabulary($id: ID!) { getVocabulary(id: $id) { id key name } }`,\n { id },\n actor\n );\n return data.getVocabulary ?? null;\n }\n\n async getVocabularyByKey(key: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabularyByKey: TagVocabularyRef | null }>(\n `query GetVocabularyByKey($key: String!) { getVocabularyByKey(key: $key) { id key name } }`,\n { key },\n actor\n );\n return data.getVocabularyByKey ?? null;\n }\n\n /** Create a WORKSPACE-scoped, multi-valued, open (custom tags allowed) string vocabulary. */\n async createVocabulary(vocabulary: TagVocabularyConfig, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ createVocabulary: TagVocabularyRef | null }>(\n `mutation CreateVocabulary($input: CreateVocabularyInput!) {\n createVocabulary(input: $input) { id key name }\n }`,\n {\n input: {\n key: requireNonEmpty(vocabulary.key, 'vocabulary.key'),\n name: requireNonEmpty(vocabulary.name, 'vocabulary.name'),\n description: vocabulary.description,\n scope: 'WORKSPACE',\n dataType: 'STRING',\n cardinality: 'MULTIPLE',\n allowCustomTags: true,\n },\n },\n actor\n );\n return data.createVocabulary ?? null;\n }\n\n // ── Transport ─────────────────────────────────────────────────────────\n\n private requireActor(actor: TagActor): TagActor {\n if (!actor.actorId?.trim() || !actor.workspaceId?.trim()) {\n throw new EntityTagsError('MISSING_CONTEXT', 'Tag operations need an authenticated actor and a workspace');\n }\n return actor;\n }\n\n private getClient(): Promise<TagsGatewayClient> {\n if (!this.clientPromise) {\n const option = this.clientOption;\n this.clientPromise = (async (): Promise<TagsGatewayClient> => {\n if (typeof option === 'function') return option();\n if (option) return option;\n // Dynamic import keeps the gateway client (and its JWT/crypto deps) out of\n // the static module graph of `@burdenoff/be-sdk/tags` consumers.\n const gateway = await import('../gateway/client.js');\n if (this.serviceName) {\n return new gateway.GatewayClient({\n layer: 'wspace',\n serviceName: this.serviceName,\n serviceIdentity: this.serviceName,\n });\n }\n return gateway.createGatewayClientFromEnv();\n })();\n // A failed construction (bad env) must not be cached forever.\n this.clientPromise.catch(() => {\n this.clientPromise = null;\n });\n }\n return this.clientPromise;\n }\n\n private async request<T>(query: string, variables: Record<string, unknown>, actor: TagActor): Promise<T> {\n const { actorId, workspaceId, actorType } = this.requireActor(actor);\n const client = await this.getClient();\n const response = await client.internalQuery<T>({\n query,\n variables,\n timeout: this.requestTimeoutMs,\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType || 'user',\n 'x-workspace-id': workspaceId,\n },\n });\n if (response.errors?.length) {\n throw new EntityTagsError(\n 'UPSTREAM_ERROR',\n `wspace-tags-svc error: ${response.errors.map((error) => error.message).join('; ')}`,\n { errors: response.errors }\n );\n }\n if (!response.data) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no data');\n }\n return response.data;\n }\n}\n","/**\n * Entity tags — SDL generator.\n *\n * One fixed SDL fragment cannot be shared: two subgraphs declaring the same\n * non-`@shareable` value type (`EntityTagAssignment`, `AvailableTag`, …) fail\n * Federation composition. {@link buildEntityTagsSdl} therefore emits the whole\n * tag surface under a per-service prefix (names from `./naming.ts`), with a\n * static `@rbac` directive on every root field — the gateway enforces RBAC from\n * the composed supergraph and needs a literal action/resource per field.\n *\n * The SDL references `@rbac`, `JSON`, `DateTime` and the federated\n * `UniversalTag` entity, which the host subgraph already declares (pass\n * `includeUniversalTagStub: true` if it does not declare `UniversalTag` yet).\n */\nimport { EntityTagsError } from './errors.js';\nimport { entityTagsFieldNames, entityTagsTypeNames, type EntityTagsTypeNames } from './naming.js';\n\nconst TYPE_NAME_PATTERN = /^[A-Z]\\w*$/;\nconst RBAC_TOKEN_PATTERN = /^[a-z0-9][a-z0-9:_-]*$/i;\n\n/** The `@rbac` arguments stamped on the generated root fields. */\nexport interface EntityTagsRbacOptions {\n /** RBAC resource the service already gates its entities on, e.g. `workflow`, `agent`. */\n resource: string;\n /** Default `wspace`. */\n scopeType?: string;\n /** Action for the read fields. Default `read`. */\n readAction?: string;\n /** Action for tag/untag/replace. Default `update`. */\n updateAction?: string;\n /** Action for creating a workspace tag. Default `create`. */\n createAction?: string;\n}\n\nexport interface EntityTagsSdlOptions {\n /** PascalCase service prefix, e.g. `Fluidgrids` → `fluidgridsEntityTags`, `FluidgridsTagAssignment`. */\n prefix: string;\n /** Product name used in field descriptions. Defaults to `prefix`. */\n productLabel?: string;\n rbac: EntityTagsRbacOptions;\n /** Types (owned elsewhere in the subgraph) that get a `tagAssignments` field. */\n extendTypes?: readonly string[];\n /** Override generated type names, for services with already-published legacy names. */\n typeNames?: Partial<EntityTagsTypeNames>;\n /** Types the subgraph already declares elsewhere: referenced, not declared. */\n externalTypes?: readonly (keyof EntityTagsTypeNames)[];\n /** Also emit the `…EntitiesByTags` query (server-side filter-by-tag). Default `false`. */\n includeEntitiesByTags?: boolean;\n /** Also declare the non-resolvable `UniversalTag @key(fields: \"id\")` stub. Default `false`. */\n includeUniversalTagStub?: boolean;\n}\n\n/** Non-resolvable stub for the tags-svc-owned `UniversalTag` entity. */\nexport const UNIVERSAL_TAG_STUB_SDL = /* GraphQL */ `\n \"UniversalTag is owned by wspace-tags-svc; only its key is resolvable here.\"\n type UniversalTag @key(fields: \"id\", resolvable: false) {\n id: ID!\n }\n`;\n\nfunction rbacToken(value: string, field: string): string {\n if (!RBAC_TOKEN_PATTERN.test(value)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags rbac.${field} \"${value}\" is not a valid RBAC token`, {\n field,\n value,\n });\n }\n return value;\n}\n\nfunction rbacDirective(action: string, resource: string, scopeType: string): string {\n return `@rbac(action: \"${action}\", resource: \"${resource}\", scopeType: \"${scopeType}\")`;\n}\n\nfunction sanitizeDescription(value: string): string {\n // Config-time text inside a \"...\" description: no quote or backslash may end/escape it.\n return value.replace(/[\"\\\\]/g, \"'\").replace(/\\s+/g, ' ').trim();\n}\n\nexport function buildEntityTagsSdl(options: EntityTagsSdlOptions): string {\n const fields = entityTagsFieldNames(options.prefix);\n const types = entityTagsTypeNames(options.prefix, options.typeNames);\n const external = new Set<keyof EntityTagsTypeNames>(options.externalTypes ?? []);\n const label = sanitizeDescription(options.productLabel ?? options.prefix);\n\n const resource = rbacToken(options.rbac.resource, 'resource');\n const scopeType = rbacToken(options.rbac.scopeType ?? 'wspace', 'scopeType');\n const read = rbacDirective(rbacToken(options.rbac.readAction ?? 'read', 'readAction'), resource, scopeType);\n const update = rbacDirective(rbacToken(options.rbac.updateAction ?? 'update', 'updateAction'), resource, scopeType);\n const create = rbacDirective(rbacToken(options.rbac.createAction ?? 'create', 'createAction'), resource, scopeType);\n\n const extendTypes = [...new Set(options.extendTypes ?? [])];\n for (const typeName of extendTypes) {\n if (!TYPE_NAME_PATTERN.test(typeName)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Cannot extend \"${typeName}\": not a valid type name`, {\n typeName,\n });\n }\n }\n\n const blocks: string[] = [];\n const emitType = (role: keyof EntityTagsTypeNames, sdl: string): void => {\n if (!external.has(role)) blocks.push(sdl);\n };\n\n if (options.includeUniversalTagStub) blocks.push(UNIVERSAL_TAG_STUB_SDL.trim());\n\n emitType(\n 'getEntityTagsInput',\n `input ${types.getEntityTagsInput} {\n entityType: String!\n entityId: ID!\n}`\n );\n emitType(\n 'tagEntityInput',\n `input ${types.tagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n \"AssignmentSource (MANUAL, AUTOMATIC, IMPORTED, ...). Defaults to the service default.\"\n source: String\n metadata: JSON\n}`\n );\n emitType(\n 'untagEntityInput',\n `input ${types.untagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n}`\n );\n emitType(\n 'replaceEntityTagsInput',\n `input ${types.replaceEntityTagsInput} {\n entityType: String!\n entityId: ID!\n tagIds: [ID!]!\n}`\n );\n emitType(\n 'createTagInput',\n `input ${types.createTagInput} {\n \"Optional. When omitted the tag goes to the workspace's default ${label} vocabulary (created on first use).\"\n vocabularyId: ID\n label: String!\n color: String\n}`\n );\n emitType(\n 'tagInfo',\n `\"Inline (non-federated) tag projection, so clients render labels without a federated round-trip.\"\ntype ${types.tagInfo} {\n id: ID!\n key: String\n label: String\n color: String\n}`\n );\n emitType(\n 'tagAssignment',\n `\"A tag assigned to a ${label} entity.\"\ntype ${types.tagAssignment} {\n id: ID!\n tagId: ID!\n \"Federated UniversalTag reference (owned by wspace-tags-svc). Prefer tagInfo for label/colour.\"\n tag: UniversalTag\n \"Inline projection of the tag (key/label/colour).\"\n tagInfo: ${types.tagInfo}\n entityType: String!\n entityId: ID!\n source: String!\n assignedBy: ID\n assignedAt: DateTime\n validFrom: DateTime\n validTo: DateTime\n metadata: JSON\n}`\n );\n emitType(\n 'availableTag',\n `\"An assignable workspace tag.\"\ntype ${types.availableTag} {\n id: ID!\n key: String!\n label: String!\n color: String\n}`\n );\n\n if (options.includeEntitiesByTags) {\n emitType(\n 'entitiesByTagsInput',\n `input ${types.entitiesByTagsInput} {\n entityType: String!\n tagIds: [ID!]!\n \"true = entity must carry every tag; false (default) = any of them.\"\n matchAll: Boolean\n limit: Int\n cursor: String\n}`\n );\n emitType(\n 'taggedEntityPage',\n `\"Ids of entities carrying the requested tags.\"\ntype ${types.taggedEntityPage} {\n entityIds: [ID!]!\n total: Int!\n hasMore: Boolean!\n nextCursor: String\n}`\n );\n }\n\n const queryFields = [\n ` \"Tags currently assigned to a ${label} entity\"\n ${fields.entityTags}(input: ${types.getEntityTagsInput}!): [${types.tagAssignment}!]! ${read}`,\n ` \"Search assignable tags in the workspace\"\n ${fields.searchTags}(query: String!, limit: Int): [${types.availableTag}!]! ${read}`,\n ` \"List assignable tags in the workspace\"\n ${fields.availableTags}(limit: Int): [${types.availableTag}!]! ${read}`,\n ];\n if (options.includeEntitiesByTags) {\n queryFields.push(` \"Ids of ${label} entities carrying the given tags (filter-by-tag)\"\n ${fields.entitiesByTags}(input: ${types.entitiesByTagsInput}!): ${types.taggedEntityPage}! ${read}`);\n }\n blocks.push(`extend type Query {\\n${queryFields.join('\\n\\n')}\\n}`);\n\n blocks.push(`extend type Mutation {\n \"Assign a tag to a ${label} entity\"\n ${fields.tagEntity}(input: ${types.tagEntityInput}!): ${types.tagAssignment}! ${update}\n\n \"Remove a tag from a ${label} entity\"\n ${fields.untagEntity}(input: ${types.untagEntityInput}!): Boolean! ${update}\n\n \"Replace the full tag set on a ${label} entity\"\n ${fields.replaceEntityTags}(input: ${types.replaceEntityTagsInput}!): [${types.tagAssignment}!]! ${update}\n\n \"Create a new assignable tag (inline creation from a picker)\"\n ${fields.createTag}(input: ${types.createTagInput}!): ${types.availableTag}! ${create}\n}`);\n\n for (const typeName of extendTypes) {\n blocks.push(`extend type ${typeName} {\n \"Structured tag assignments (wspace-tags-svc).\"\n tagAssignments: [${types.tagAssignment}!]!\n}`);\n }\n\n return `${blocks.join('\\n\\n')}\\n`;\n}\n","/**\n * Entity tags — resolver factory.\n *\n * Builds the Query / Mutation / `tagAssignments` resolvers that match the SDL\n * from {@link buildEntityTagsSdl} for the same `prefix` (both derive names from\n * `./naming.ts`). The service supplies only what differs: how to read the actor\n * off its context, which GraphQL types map to which entity types, how to map\n * errors onto its i18n errors, and optional ownership/audit hooks.\n *\n * @example\n * ```ts\n * import { buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const { Query, Mutation, types } = createEntityTagResolvers({\n * prefix: 'Fluidgrids',\n * adapter: entityTags,\n * entities: {\n * WorkflowDefinition: { entityType: 'FLUIDGRIDS_WORKFLOW', entityId: (p) => String(p.workflowKey ?? '') },\n * WorkflowRun: { entityType: 'FLUIDGRIDS_RUN' },\n * },\n * mapError: (error, ctx) => workflowError(`tags.errors.${error.code}`, error.graphqlCode, ctx, error.details),\n * });\n * ```\n */\nimport { GraphQLError } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { TagsGatewayAdapter } from './adapter.js';\nimport { EntityTagsError, isEntityTagsError } from './errors.js';\nimport { entityTagsFieldNames } from './naming.js';\nimport type { AvailableTag, EntityTagAssignment, TagActor, TagActorType, TaggedEntityPage } from './types.js';\nimport { TAG_ACTOR_TYPES } from './types.js';\n\n/** Maps a GraphQL object type onto the entity type and id its tags are stored under. */\nexport interface EntityTagBinding {\n entityType: string;\n /**\n * Entity id for a parent object. Defaults to `parent.id`. Use a stable logical id\n * when rows are versioned (FluidGrids tags `workflowKey`, not the per-version row id).\n */\n entityId?: (parent: Record<string, unknown>) => string | null | undefined;\n}\n\nexport type EntityTagOperation = 'tag' | 'untag' | 'replace' | 'createTag';\n\n/** Emitted after a successful write, for audit/activity logging. */\nexport interface EntityTagMutationEvent {\n operation: EntityTagOperation;\n /** Root field name, e.g. `tagFluidgridsEntity`. */\n fieldName: string;\n actor: TagActor;\n entityType?: string;\n entityId?: string;\n tagId?: string;\n tagIds?: string[];\n source?: string;\n /** For `createTag`. */\n tag?: AvailableTag;\n vocabularyId?: string;\n}\n\n/** Passed to `authorizeEntity` before any entity-addressed operation. */\nexport interface EntityTagAccessCheck {\n entityType: string;\n entityId: string;\n access: 'read' | 'write';\n actor: TagActor;\n}\n\nexport interface CreateEntityTagResolversOptions<TContext> {\n /** Same prefix as passed to `buildEntityTagsSdl`. */\n prefix: string;\n adapter: TagsGatewayAdapter;\n /** GraphQL type name → binding, for the `tagAssignments` field on each extended type. */\n entities?: Readonly<Record<string, EntityTagBinding>>;\n /**\n * Reads the caller off the request context. Default: be-sdk server context\n * (`context.actor.{id,type}`, `context.workspace.id`), falling back to flat\n * `context.actorId` / `context.workspaceId`.\n */\n getActor?: (context: TContext) => TagActor;\n /**\n * Ownership check for entity-addressed operations (throw to deny). Use it to\n * confirm the entity exists in the caller's workspace before tags are read or\n * written for an arbitrary `entityId`; throw NOT_FOUND, never FORBIDDEN.\n */\n authorizeEntity?: (check: EntityTagAccessCheck, context: TContext) => void | Promise<void>;\n /** Called after each successful write. Failures are logged, never surfaced. */\n onMutation?: (event: EntityTagMutationEvent, context: TContext) => void | Promise<void>;\n /** Map an adapter error onto the service's own (i18n) GraphQL error. */\n mapError?: (error: EntityTagsError, context: TContext) => Error;\n /** Must match `includeEntitiesByTags` on the SDL. Default `false`. */\n includeEntitiesByTags?: boolean;\n}\n\ntype Resolver<TArgs, TResult, TContext> = (parent: unknown, args: TArgs, context: TContext) => Promise<TResult>;\n\ntype TagAssignmentsResolver<TContext> = (\n parent: Record<string, unknown>,\n args: unknown,\n context: TContext\n) => Promise<EntityTagAssignment[]>;\n\ninterface EntityRefInput {\n entityType: string;\n entityId: string;\n}\n\nexport interface EntityTagResolvers<TContext> {\n Query: Record<string, Resolver<never, unknown, TContext>>;\n Mutation: Record<string, Resolver<never, unknown, TContext>>;\n /** `{ [GraphQLTypeName]: { tagAssignments } }`, ready to spread into the resolver map. */\n types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }>;\n}\n\nfunction readRecord(value: unknown, key: string): unknown {\n if (value === null || typeof value !== 'object') return undefined;\n return (value as Record<string, unknown>)[key];\n}\n\nfunction readString(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction toActorType(value: unknown): TagActorType {\n return TAG_ACTOR_TYPES.find((candidate) => candidate === value) ?? 'user';\n}\n\n/** Default actor reader for the be-sdk server context shape. */\nexport function defaultTagActor(context: unknown): TagActor {\n const actor = readRecord(context, 'actor');\n const workspace = readRecord(context, 'workspace');\n return {\n actorId: readString(readRecord(actor, 'id')) || readString(readRecord(context, 'actorId')),\n actorType: toActorType(readRecord(actor, 'type') ?? readRecord(context, 'actorType')),\n workspaceId: readString(readRecord(workspace, 'id')) || readString(readRecord(context, 'workspaceId')),\n };\n}\n\nfunction defaultMapError(error: EntityTagsError): Error {\n if (error.code === 'UPSTREAM_ERROR' || error.code === 'CONFIGURATION_ERROR') {\n // Upstream payloads can carry internal detail; log it, return a generic message.\n logger.error('[be-sdk/tags] Tag operation failed', { code: error.code, message: error.message });\n return new GraphQLError('Tag operation failed', { extensions: { code: error.graphqlCode } });\n }\n return new GraphQLError(error.message, { extensions: { code: error.graphqlCode, reason: error.code } });\n}\n\nexport function createEntityTagResolvers<TContext>(\n options: CreateEntityTagResolversOptions<TContext>\n): EntityTagResolvers<TContext> {\n const { adapter } = options;\n const fields = entityTagsFieldNames(options.prefix);\n const getActor = options.getActor ?? ((context: TContext) => defaultTagActor(context));\n const mapError = options.mapError ?? ((error: EntityTagsError) => defaultMapError(error));\n\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n if (!adapter.isValidEntityType(binding.entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `${typeName} is bound to entity type \"${binding.entityType}\", which the adapter does not register`,\n { typeName, entityType: binding.entityType }\n );\n }\n }\n\n const guard = async <T>(context: TContext, run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n if (isEntityTagsError(error)) throw mapError(error, context);\n throw error;\n }\n };\n\n const authorize = async (\n input: EntityRefInput,\n access: EntityTagAccessCheck['access'],\n actor: TagActor,\n context: TContext\n ): Promise<void> => {\n adapter.assertEntityType(input.entityType);\n if (!input.entityId?.trim()) {\n throw new EntityTagsError('INVALID_INPUT', 'entityId is required', { field: 'entityId' });\n }\n if (options.authorizeEntity) {\n await options.authorizeEntity({ entityType: input.entityType, entityId: input.entityId, access, actor }, context);\n }\n };\n\n const notify = async (event: EntityTagMutationEvent, context: TContext): Promise<void> => {\n if (!options.onMutation) return;\n try {\n await options.onMutation(event, context);\n } catch (error) {\n logger.warn('[be-sdk/tags] onMutation hook failed', {\n fieldName: event.fieldName,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n const Query: Record<string, Resolver<never, unknown, TContext>> = {};\n const Mutation: Record<string, Resolver<never, unknown, TContext>> = {};\n\n const entityTags: Resolver<{ input: EntityRefInput }, EntityTagAssignment[], TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'read', actor, context);\n return adapter.getEntityTags(input.entityType, input.entityId, actor);\n });\n Query[fields.entityTags] = entityTags;\n\n const searchTags: Resolver<{ query: string; limit?: number | null }, AvailableTag[], TContext> = (\n _parent,\n { query, limit },\n context\n ) => guard(context, () => adapter.searchTags(query, getActor(context), limit));\n Query[fields.searchTags] = searchTags;\n\n const availableTags: Resolver<{ limit?: number | null }, AvailableTag[], TContext> = (_parent, { limit }, context) =>\n guard(context, () => adapter.getAvailableTags(getActor(context), limit));\n Query[fields.availableTags] = availableTags;\n\n if (options.includeEntitiesByTags) {\n const entitiesByTags: Resolver<\n {\n input: {\n entityType: string;\n tagIds: string[];\n matchAll?: boolean | null;\n limit?: number | null;\n cursor?: string | null;\n };\n },\n TaggedEntityPage,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, () =>\n adapter.findEntityIdsByTags(input.entityType, input.tagIds, getActor(context), {\n matchAll: input.matchAll ?? false,\n limit: input.limit,\n cursor: input.cursor,\n })\n );\n Query[fields.entitiesByTags] = entitiesByTags;\n }\n\n const tagEntity: Resolver<\n { input: EntityRefInput & { tagId: string; source?: string | null; metadata?: Record<string, unknown> | null } },\n EntityTagAssignment,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignment = await adapter.tagEntity(\n input.entityType,\n input.entityId,\n { tagId: input.tagId, source: input.source, metadata: input.metadata },\n actor\n );\n await notify(\n {\n operation: 'tag',\n fieldName: fields.tagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n source: assignment.source,\n },\n context\n );\n return assignment;\n });\n Mutation[fields.tagEntity] = tagEntity;\n\n const untagEntity: Resolver<{ input: EntityRefInput & { tagId: string } }, boolean, TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const removed = await adapter.untagEntity(input.entityType, input.entityId, input.tagId, actor);\n if (removed) {\n await notify(\n {\n operation: 'untag',\n fieldName: fields.untagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n },\n context\n );\n }\n return removed;\n });\n Mutation[fields.untagEntity] = untagEntity;\n\n const replaceEntityTags: Resolver<\n { input: EntityRefInput & { tagIds: string[] } },\n EntityTagAssignment[],\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignments = await adapter.replaceEntityTags(input.entityType, input.entityId, input.tagIds, actor);\n await notify(\n {\n operation: 'replace',\n fieldName: fields.replaceEntityTags,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagIds: [...new Set(input.tagIds)],\n },\n context\n );\n return assignments;\n });\n Mutation[fields.replaceEntityTags] = replaceEntityTags;\n\n const createTag: Resolver<\n { input: { vocabularyId?: string | null; label: string; color?: string | null } },\n AvailableTag,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n const vocabularyId =\n input.vocabularyId !== undefined && input.vocabularyId !== null\n ? input.vocabularyId\n : await adapter.ensureWorkspaceVocabulary(actor);\n const tag = await adapter.createTag({ label: input.label, color: input.color, vocabularyId }, actor);\n await notify({ operation: 'createTag', fieldName: fields.createTag, actor, tag, vocabularyId }, context);\n return tag;\n });\n Mutation[fields.createTag] = createTag;\n\n const types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }> = {};\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n const selectId = binding.entityId ?? ((parent: Record<string, unknown>) => readString(parent['id']));\n types[typeName] = {\n tagAssignments: async (parent, _args, context) => {\n const entityId = selectId(parent);\n if (!entityId) return [];\n try {\n return await adapter.getEntityTags(binding.entityType, entityId, getActor(context));\n } catch (error) {\n // The field is non-nullable decoration: a tags-svc outage must never fail\n // the parent query (a workflow list, a run page, …).\n logger.warn('[be-sdk/tags] Failed to resolve tagAssignments', {\n typeName,\n entityType: binding.entityType,\n entityId,\n error: error instanceof Error ? error.message : String(error),\n });\n return [];\n }\n },\n };\n }\n\n return { Query, Mutation, types };\n}\n","/**\n * @burdenoff/be-sdk/tags\n *\n * Shared \"tag my entities\" surface for product services, backed by\n * wspace-tags-svc through the internal workspace gateway:\n *\n * - {@link TagsGatewayAdapter} — the configurable adapter (entity types, default\n * vocabulary, default source) that replaces the per-service EntityTagAdapter copies.\n * - {@link buildEntityTagsSdl} — the per-service, prefixed SDL (unique type names so\n * subgraphs never collide in composition; static `@rbac` on every root field).\n * - {@link createEntityTagResolvers} — the matching Query / Mutation /\n * `tagAssignments` resolvers, with ownership, audit and error-mapping hooks.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter, buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const adapter = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n * export const typeDefs = buildEntityTagsSdl({\n * prefix: 'Fluidgrids',\n * productLabel: 'FluidGrids',\n * rbac: { resource: 'workflow' },\n * extendTypes: ['WorkflowDefinition', 'WorkflowRun'],\n * });\n * export const resolvers = createEntityTagResolvers({ prefix: 'Fluidgrids', adapter, entities: { … } });\n * ```\n */\n\nexport {\n TAG_ACTOR_TYPES,\n TAG_ASSIGNMENT_SOURCES,\n type AvailableTag,\n type CreateTagOptions,\n type EntityTagAssignment,\n type EntityTagInfo,\n type FindEntitiesByTagsOptions,\n type RawTagAssignment,\n type TagActor,\n type TagActorType,\n type TagAssignmentSource,\n type TagEntityOptions,\n type TaggedEntityPage,\n type TagsGatewayClient,\n type TagVocabularyConfig,\n type TagVocabularyRef,\n} from './types.js';\n\nexport { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, isEntityTagsError, type EntityTagsErrorCode } from './errors.js';\n\nexport {\n assertTagPrefix,\n entityTagsFieldNames,\n entityTagsTypeNames,\n type EntityTagsFieldNames,\n type EntityTagsTypeNames,\n} from './naming.js';\n\nexport { TagsGatewayAdapter, mapTagAssignment, slugifyTagKey, type TagsGatewayAdapterOptions } from './adapter.js';\n\nexport {\n UNIVERSAL_TAG_STUB_SDL,\n buildEntityTagsSdl,\n type EntityTagsRbacOptions,\n type EntityTagsSdlOptions,\n} from './sdl.js';\n\nexport {\n createEntityTagResolvers,\n defaultTagActor,\n type CreateEntityTagResolversOptions,\n type EntityTagAccessCheck,\n type EntityTagBinding,\n type EntityTagMutationEvent,\n type EntityTagOperation,\n type EntityTagResolvers,\n} from './resolvers.js';\n"],"mappings":";;;;;;AAWA,MAAa,kBAAkB;CAAC;CAAQ;CAAO;CAAW;AAAa;;AAevE,MAAa,yBAAyB;CAAC;CAAa;CAAY;CAAY;CAAa;CAAU;AAAU;;;;ACH7G,MAAa,4BAAiE;CAC5E,qBAAqB;CACrB,gBAAgB;CAChB,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CAChB,qBAAqB;AACvB;AAEA,IAAa,kBAAb,cAAqC,MAAM;CACzC,AAAS;CACT,AAAS;CAET,YAAY,MAA2B,SAAiB,UAAmC,CAAC,GAAG;EAC7F,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;CACjB;;CAGA,IAAI,cAAsB;EACxB,OAAO,0BA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AC9B,MAAM,eACJ,MAAM,iBAAiB,UAAa,MAAM,iBAAiB,OACvD,MAAM,eACN,MAAM,QAAQ,0BAA0B,KAAK;EACnD,MAAM,MAAM,MAAM,QAAQ,UAAU;GAAE,OAAO,MAAM;GAAO,OAAO,MAAM;GAAO;EAAa,GAAG,KAAK;EACnG,MAAM,OAAO;GAAE,WAAW;GAAa,WAAW,OAAO;GAAW;GAAO;GAAK;EAAa,GAAG,OAAO;EACvG,OAAO;CACT,CAAC;CACH,SAAS,OAAO,aAAa;CAE7B,MAAM,QAA8E,CAAC;CACrF,KAAK,MAAM,CAAC,UAAU,YAAY,OAAO,QAAQ,QAAQ,YAAY,CAAC,CAAC,GAAG;EACxE,MAAM,WAAW,QAAQ,cAAc,WAAoC,WAAW,OAAO,KAAK;EAClG,MAAM,YAAY,EAChB,gBAAgB,OAAO,QAAQ,OAAO,YAAY;GAChD,MAAM,WAAW,SAAS,MAAM;GAChC,IAAI,CAAC,UAAU,OAAO,CAAC;GACvB,IAAI;IACF,OAAO,MAAM,QAAQ,cAAc,QAAQ,YAAY,UAAU,SAAS,OAAO,CAAC;GACpF,SAAS,OAAO;IAGd,OAAO,KAAK,kDAAkD;KAC5D;KACA,YAAY,QAAQ;KACpB;KACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,CAAC;IACD,OAAO,CAAC;GACV;EACF,EACF;CACF;CAEA,OAAO;EAAE;EAAO;EAAU;CAAM;AAClC"}
1
+ {"version":3,"file":"tags-C316oA9r.js","names":[],"sources":["../src/tags/types.ts","../src/tags/errors.ts","../src/tags/naming.ts","../src/tags/adapter.ts","../src/tags/sdl.ts","../src/tags/resolvers.ts","../src/tags/index.ts"],"sourcesContent":["/**\n * Entity tags — shared types.\n *\n * Every product service that lets users tag its own entities talks to the one\n * polymorphic tag owner, **wspace-tags-svc**, through the internal workspace\n * gateway. These types describe both the tags-svc wire shape and the\n * projection the service publishes in its own subgraph.\n */\nimport type { GraphQLRequestOptions, GraphQLResponse } from '../gateway/types.js';\n\n/** Actor types the gateway forwards in `x-actor-type`. */\nexport const TAG_ACTOR_TYPES = ['user', 'app', 'service', 'super_admin'] as const;\n\nexport type TagActorType = (typeof TAG_ACTOR_TYPES)[number];\n\n/** The caller a tag operation runs on behalf of (forwarded as `x-actor-*` / `x-workspace-id`). */\nexport interface TagActor {\n /** `x-actor-id` — the user/app/service id the gateway authenticated. */\n actorId: string;\n /** `x-workspace-id` — tags-svc scopes every vocabulary, tag and assignment by it. */\n workspaceId: string;\n /** `x-actor-type`; defaults to `user`. */\n actorType?: TagActorType;\n}\n\n/** `AssignmentSource` enum members accepted by wspace-tags-svc. */\nexport const TAG_ASSIGNMENT_SOURCES = ['AUTOMATIC', 'COMPUTED', 'IMPORTED', 'INHERITED', 'MANUAL', 'MIGRATED'] as const;\n\nexport type TagAssignmentSource = (typeof TAG_ASSIGNMENT_SOURCES)[number];\n\n/** `UniversalTagAssignment` as it comes back over the wire from wspace-tags-svc. */\nexport interface RawTagAssignment {\n id: string;\n tagId: string;\n entityType: string;\n entityId: string;\n source: string;\n assignedById?: string | null;\n createdAt?: string | null;\n validFrom?: string | null;\n validTo?: string | null;\n metadata?: unknown;\n tag?: { id: string; key?: string | null; label?: string | null; color?: string | null } | null;\n}\n\n/** Inline (non-federated) tag projection so clients render labels in one round-trip. */\nexport interface EntityTagInfo {\n id: string;\n key: string | null;\n label: string | null;\n color: string | null;\n}\n\n/** A tag assigned to one of the service's entities, in the shape its subgraph publishes. */\nexport interface EntityTagAssignment {\n id: string;\n tagId: string;\n /** Federated `UniversalTag` reference — only `id` resolves locally; tags-svc owns the rest. */\n tag: { id: string } | null;\n tagInfo: EntityTagInfo | null;\n entityType: string;\n entityId: string;\n source: string;\n assignedBy: string | null;\n assignedAt: Date | null;\n validFrom: Date | null;\n validTo: Date | null;\n metadata: unknown;\n}\n\n/** An assignable workspace tag. */\nexport interface AvailableTag {\n id: string;\n key: string;\n label: string;\n color: string | null;\n}\n\n/** Minimal vocabulary reference returned by tags-svc. */\nexport interface TagVocabularyRef {\n id: string;\n key: string;\n name: string;\n}\n\n/** The workspace-scoped vocabulary that inline-created tags land in. */\nexport interface TagVocabularyConfig {\n /** Stable vocabulary key, e.g. `fluidgrids-tags`. Looked up first, created when missing. */\n key: string;\n /** Display name used when the vocabulary has to be created. */\n name: string;\n description?: string;\n /**\n * A pinned vocabulary id. Used when it exists in the caller's workspace; ignored\n * (falls back to `key`) when it does not, so one id never leaks across workspaces.\n */\n id?: string;\n}\n\n/** Options for {@link TagsGatewayAdapter.tagEntity}. */\nexport interface TagEntityOptions {\n tagId: string;\n source?: string | null;\n validFrom?: Date | null;\n validTo?: Date | null;\n metadata?: Record<string, unknown> | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.createTag}. */\nexport interface CreateTagOptions {\n label: string;\n color?: string | null;\n /**\n * Target vocabulary. `undefined`/`null` resolves (or creates) the adapter's default\n * vocabulary. Any explicit value, even an empty string, is sent as-is so an unknown id\n * surfaces as a tags-svc error instead of silently misfiling the tag.\n */\n vocabularyId?: string | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.findEntityIdsByTags}. */\nexport interface FindEntitiesByTagsOptions {\n /** `true` = entity must carry every tag; `false` (default) = any of them. */\n matchAll?: boolean;\n /** Clamped to 1..200; default 50. */\n limit?: number | null;\n cursor?: string | null;\n}\n\n/** One page of entity ids carrying the requested tags. */\nexport interface TaggedEntityPage {\n entityIds: string[];\n total: number;\n hasMore: boolean;\n nextCursor: string | null;\n}\n\n/** The slice of the be-sdk `GatewayClient` the adapter needs (lets tests pass a fake). */\nexport interface TagsGatewayClient {\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n}\n","/**\n * Entity tags — error type.\n *\n * Services map {@link EntityTagsError} onto their own i18n GraphQL errors (see the\n * `invalidEntityTypeError` / `mapError` hooks of `createEntityTagResolvers`); the\n * `code` is stable so that mapping never has to parse messages.\n */\n\nexport type EntityTagsErrorCode =\n /** `entityType` is not one the service registered as taggable. */\n | 'INVALID_ENTITY_TYPE'\n /** `source` is not a tags-svc `AssignmentSource`. */\n | 'INVALID_SOURCE'\n /** A required argument (entity id, tag id, label, …) is empty. */\n | 'INVALID_INPUT'\n /** No actor/workspace on the request — tags are always workspace-scoped. */\n | 'MISSING_CONTEXT'\n /** tags-svc answered without the expected payload. */\n | 'UPSTREAM_ERROR'\n /** The adapter / resolver factory was configured inconsistently (thrown at boot). */\n | 'CONFIGURATION_ERROR';\n\n/** GraphQL `extensions.code` each {@link EntityTagsErrorCode} should surface as. */\nexport const ENTITY_TAGS_GRAPHQL_CODES: Record<EntityTagsErrorCode, string> = {\n INVALID_ENTITY_TYPE: 'BAD_USER_INPUT',\n INVALID_SOURCE: 'BAD_USER_INPUT',\n INVALID_INPUT: 'BAD_USER_INPUT',\n MISSING_CONTEXT: 'UNAUTHENTICATED',\n UPSTREAM_ERROR: 'INTERNAL_SERVER_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_SERVER_ERROR',\n};\n\nexport class EntityTagsError extends Error {\n readonly code: EntityTagsErrorCode;\n readonly details: Record<string, unknown>;\n\n constructor(code: EntityTagsErrorCode, message: string, details: Record<string, unknown> = {}) {\n super(message);\n this.name = 'EntityTagsError';\n this.code = code;\n this.details = details;\n }\n\n /** The GraphQL `extensions.code` this error maps to. */\n get graphqlCode(): string {\n return ENTITY_TAGS_GRAPHQL_CODES[this.code];\n }\n}\n\nexport function isEntityTagsError(error: unknown): error is EntityTagsError {\n return error instanceof EntityTagsError;\n}\n","/**\n * Entity tags — GraphQL naming.\n *\n * Every service in the workspaces supergraph publishes its own tag surface, so\n * every type and root field must be unique to the service: unprefixed\n * `EntityTagAssignment` / `AvailableTag` / `EntityTagInfo` declared by two\n * subgraphs are non-shareable value types and break composition. The SDL\n * builder and the resolver factory both derive their names from here, so a\n * service's schema and its resolver map can never drift apart.\n */\nimport { EntityTagsError } from './errors.js';\n\nconst PREFIX_PATTERN = /^[A-Z][A-Za-z0-9]*$/;\n\n/** Root field names, derived from the service prefix (`Fluidgrids` → `fluidgridsEntityTags`, …). */\nexport interface EntityTagsFieldNames {\n entityTags: string;\n searchTags: string;\n availableTags: string;\n entitiesByTags: string;\n tagEntity: string;\n untagEntity: string;\n replaceEntityTags: string;\n createTag: string;\n}\n\n/** Type / input names the tag surface declares. */\nexport interface EntityTagsTypeNames {\n getEntityTagsInput: string;\n tagEntityInput: string;\n untagEntityInput: string;\n replaceEntityTagsInput: string;\n createTagInput: string;\n entitiesByTagsInput: string;\n tagInfo: string;\n tagAssignment: string;\n availableTag: string;\n taggedEntityPage: string;\n}\n\nexport function assertTagPrefix(prefix: string): void {\n if (!PREFIX_PATTERN.test(prefix)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags prefix must be PascalCase ([A-Z][A-Za-z0-9]*), got \"${prefix}\"`,\n { prefix }\n );\n }\n}\n\nfunction lowerFirst(value: string): string {\n return value.charAt(0).toLowerCase() + value.slice(1);\n}\n\nexport function entityTagsFieldNames(prefix: string): EntityTagsFieldNames {\n assertTagPrefix(prefix);\n const camel = lowerFirst(prefix);\n return {\n entityTags: `${camel}EntityTags`,\n searchTags: `search${prefix}Tags`,\n availableTags: `available${prefix}Tags`,\n entitiesByTags: `${camel}EntitiesByTags`,\n tagEntity: `tag${prefix}Entity`,\n untagEntity: `untag${prefix}Entity`,\n replaceEntityTags: `replace${prefix}EntityTags`,\n createTag: `create${prefix}Tag`,\n };\n}\n\n/**\n * Type names for `prefix`. Defaults carry the prefix everywhere (the FluidGrids\n * convention). `overrides` exists for services that already published legacy\n * names (VibeControls ships `EntityTagAssignment`, `TagEntityInput`, …) and must\n * keep them for existing clients' fragments.\n */\nexport function entityTagsTypeNames(prefix: string, overrides: Partial<EntityTagsTypeNames> = {}): EntityTagsTypeNames {\n assertTagPrefix(prefix);\n const names: EntityTagsTypeNames = {\n getEntityTagsInput: `Get${prefix}EntityTagsInput`,\n tagEntityInput: `Tag${prefix}EntityInput`,\n untagEntityInput: `Untag${prefix}EntityInput`,\n replaceEntityTagsInput: `Replace${prefix}EntityTagsInput`,\n createTagInput: `Create${prefix}TagInput`,\n entitiesByTagsInput: `${prefix}EntitiesByTagsInput`,\n tagInfo: `${prefix}TagInfo`,\n tagAssignment: `${prefix}TagAssignment`,\n availableTag: `${prefix}AvailableTag`,\n taggedEntityPage: `${prefix}TaggedEntityPage`,\n ...overrides,\n };\n\n const seen = new Map<string, string>();\n for (const [role, name] of Object.entries(names)) {\n if (!PREFIX_PATTERN.test(name)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags type name for ${role} is not a valid type name`, {\n role,\n name,\n });\n }\n const clash = seen.get(name);\n if (clash) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags type name \"${name}\" is used for both ${clash} and ${role}`,\n {\n name,\n }\n );\n }\n seen.set(name, role);\n }\n return names;\n}\n","/**\n * TagsGatewayAdapter — one implementation of \"tag my entities\" for every service.\n *\n * Thirteen services carried their own copy of this adapter (VibeControls,\n * FluidGrids, BigConsole, files, integrations, …) and the copies drifted:\n * argument order (`userId, workspaceId` vs `workspaceId, userId`), a hard-coded\n * `x-actor-type: user`, `response.data!` non-null assertions, no source\n * validation. This class is the lifted, configurable version: a service\n * supplies its taggable entity types, its default vocabulary and (optionally)\n * the gateway client, and gets the full tag surface.\n *\n * All calls are same-layer M2M to wspace-tags-svc through the internal\n * workspace gateway (`GatewayClient.internalQuery`, which signs the service JWT);\n * the caller's actor and workspace are forwarded explicitly because tags-svc\n * scopes every vocabulary, tag and assignment by `x-workspace-id`.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter } from '@burdenoff/be-sdk/tags';\n *\n * export const entityTags = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN', 'FLUIDGRIDS_DATATABLE'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n *\n * await entityTags.tagEntity('FLUIDGRIDS_RUN', run.id, { tagId }, { actorId, workspaceId });\n * ```\n */\nimport { EntityTagsError } from './errors.js';\nimport type {\n AvailableTag,\n CreateTagOptions,\n EntityTagAssignment,\n FindEntitiesByTagsOptions,\n RawTagAssignment,\n TagActor,\n TagAssignmentSource,\n TagEntityOptions,\n TagsGatewayClient,\n TaggedEntityPage,\n TagVocabularyConfig,\n TagVocabularyRef,\n} from './types.js';\nimport { TAG_ASSIGNMENT_SOURCES } from './types.js';\n\n/** tags-svc caps; requests outside are clamped rather than rejected. */\nconst SEARCH_LIMIT = { default: 20, max: 100 };\nconst AVAILABLE_LIMIT = { default: 50, max: 200 };\nconst ENTITIES_BY_TAGS_LIMIT = { default: 50, max: 200 };\n\n/** Same-layer tag calls should fail fast; the GatewayClient default is 30s. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\n\nconst ENTITY_TYPE_PATTERN = /^[A-Z][A-Z0-9_]*$/;\n\nconst ASSIGNMENT_FIELDS =\n 'id tagId entityType entityId source assignedById createdAt validFrom validTo metadata tag { id key label color }';\n\nexport interface TagsGatewayAdapterOptions {\n /**\n * The entity types this service owns, e.g. `['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN']`.\n * UPPER_SNAKE_CASE and namespaced by product so two services never share a type.\n */\n entityTypes: readonly string[];\n /** Default vocabulary that inline-created tags (no `vocabularyId`) land in. */\n vocabulary: TagVocabularyConfig;\n /** `source` sent when a caller passes none. Default `MANUAL`. */\n defaultSource?: TagAssignmentSource;\n /**\n * Gateway client, or a factory for one. Defaults to a lazily constructed be-sdk\n * `GatewayClient` (`layer: 'wspace'`, `serviceName` below, or the\n * `SERVICE_LAYER`/`SERVICE_NAME` env when `serviceName` is omitted).\n */\n client?: TagsGatewayClient | (() => TagsGatewayClient | Promise<TagsGatewayClient>);\n /** Service name for the default GatewayClient, e.g. `wspace-workflow-svc`. */\n serviceName?: string;\n /** Per-request timeout for tags-svc calls. Default 10s. */\n requestTimeoutMs?: number;\n}\n\nfunction clampLimit(value: number | null | undefined, bounds: { default: number; max: number }): number {\n if (value === null || value === undefined || !Number.isFinite(value)) return bounds.default;\n return Math.min(Math.max(Math.trunc(value), 1), bounds.max);\n}\n\nfunction toDate(value: string | null | undefined): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction requireNonEmpty(value: string | null | undefined, field: string): string {\n const trimmed = typeof value === 'string' ? value.trim() : '';\n if (!trimmed) {\n throw new EntityTagsError('INVALID_INPUT', `${field} is required`, { field });\n }\n return trimmed;\n}\n\n/** FNV-1a, used only to give non-ASCII labels a stable, non-empty key. */\nfunction shortHash(value: string): string {\n let hash = 0x811c9dc5;\n for (const char of value) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(36);\n}\n\n/**\n * Tag key for a label: lowercase ASCII slug (`\"Needs Review!\"` → `needs-review`).\n * Labels with no ASCII letters or digits (`\"日本\"`) get `tag-<hash>` so the key is\n * never empty (tags-svc rejects an empty key) and stays stable for the same label.\n */\nexport function slugifyTagKey(label: string): string {\n const slug = label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return slug || `tag-${shortHash(label.trim())}`;\n}\n\n/** Map a tags-svc `UniversalTagAssignment` onto the published assignment shape. */\nexport function mapTagAssignment(raw: RawTagAssignment): EntityTagAssignment {\n return {\n id: raw.id,\n tagId: raw.tagId,\n entityType: raw.entityType,\n entityId: raw.entityId,\n source: raw.source,\n assignedBy: raw.assignedById ?? null,\n assignedAt: toDate(raw.createdAt) ?? toDate(raw.validFrom),\n validFrom: toDate(raw.validFrom),\n validTo: toDate(raw.validTo),\n metadata: raw.metadata ?? null,\n tag: raw.tag ? { id: raw.tag.id } : null,\n tagInfo: raw.tag\n ? {\n id: raw.tag.id,\n key: raw.tag.key ?? null,\n label: raw.tag.label ?? null,\n color: raw.tag.color ?? null,\n }\n : null,\n };\n}\n\nexport class TagsGatewayAdapter {\n readonly entityTypes: readonly string[];\n readonly vocabulary: Readonly<TagVocabularyConfig>;\n readonly defaultSource: TagAssignmentSource;\n\n private readonly entityTypeSet: ReadonlySet<string>;\n private readonly requestTimeoutMs: number;\n private readonly clientOption: TagsGatewayAdapterOptions['client'];\n private readonly serviceName: string | undefined;\n private clientPromise: Promise<TagsGatewayClient> | null = null;\n\n constructor(options: TagsGatewayAdapterOptions) {\n if (options.entityTypes.length === 0) {\n throw new EntityTagsError('CONFIGURATION_ERROR', 'TagsGatewayAdapter needs at least one entity type');\n }\n for (const entityType of options.entityTypes) {\n if (!ENTITY_TYPE_PATTERN.test(entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity type \"${entityType}\" must be UPPER_SNAKE_CASE (e.g. FLUIDGRIDS_WORKFLOW)`,\n { entityType }\n );\n }\n }\n requireNonEmpty(options.vocabulary.key, 'vocabulary.key');\n requireNonEmpty(options.vocabulary.name, 'vocabulary.name');\n const defaultSource = options.defaultSource ?? 'MANUAL';\n if (!TAG_ASSIGNMENT_SOURCES.includes(defaultSource)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Unknown default tag source \"${defaultSource}\"`);\n }\n\n this.entityTypes = Object.freeze([...new Set(options.entityTypes)]);\n this.entityTypeSet = new Set(this.entityTypes);\n this.vocabulary = Object.freeze({ ...options.vocabulary });\n this.defaultSource = defaultSource;\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.clientOption = options.client;\n this.serviceName = options.serviceName;\n }\n\n // ── Validation ────────────────────────────────────────────────────────\n\n isValidEntityType(entityType: string): boolean {\n return this.entityTypeSet.has(entityType);\n }\n\n assertEntityType(entityType: string): void {\n if (!this.isValidEntityType(entityType)) {\n throw new EntityTagsError('INVALID_ENTITY_TYPE', `Unsupported entity type \"${entityType}\"`, {\n entityType,\n supported: this.entityTypes,\n });\n }\n }\n\n /** Validate a caller-supplied source; empty means the adapter default. */\n resolveSource(source: string | null | undefined): TagAssignmentSource {\n if (source === null || source === undefined || source === '') return this.defaultSource;\n const normalized = source.toUpperCase();\n const match = TAG_ASSIGNMENT_SOURCES.find((candidate) => candidate === normalized);\n if (!match) {\n throw new EntityTagsError('INVALID_SOURCE', `Unknown tag source \"${source}\"`, {\n source,\n supported: TAG_ASSIGNMENT_SOURCES,\n });\n }\n return match;\n }\n\n // ── Assignments ───────────────────────────────────────────────────────\n\n /** Tags currently assigned to an entity. */\n async getEntityTags(entityType: string, entityId: string, actor: TagActor): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const data = await this.request<{ getEntityTags: RawTagAssignment[] | null }>(\n `query GetEntityTags($entityType: String!, $entityId: ID!) {\n getEntityTags(entityType: $entityType, entityId: $entityId) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id },\n actor\n );\n return (data.getEntityTags ?? []).map(mapTagAssignment);\n }\n\n /** Assign one tag to an entity. */\n async tagEntity(\n entityType: string,\n entityId: string,\n options: TagEntityOptions,\n actor: TagActor\n ): Promise<EntityTagAssignment> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const tagId = requireNonEmpty(options.tagId, 'tagId');\n const source = this.resolveSource(options.source);\n const context = this.requireActor(actor);\n\n const data = await this.request<{ assignTag: RawTagAssignment | null }>(\n `mutation AssignTag($input: AssignTagInput!) {\n assignTag(input: $input) { ${ASSIGNMENT_FIELDS} }\n }`,\n {\n input: {\n tagId,\n entityType,\n entityId: id,\n source,\n validFrom: options.validFrom?.toISOString(),\n validTo: options.validTo?.toISOString(),\n metadata: options.metadata ?? undefined,\n context: { workspaceId: context.workspaceId },\n },\n },\n context\n );\n if (!data.assignTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no assignment', { entityType, tagId });\n }\n return mapTagAssignment(data.assignTag);\n }\n\n /**\n * Remove a tag from an entity. Removes every assignment of that tag on the entity\n * (tags-svc allows several with different validity windows). `false` when the tag\n * was not assigned.\n */\n async untagEntity(entityType: string, entityId: string, tagId: string, actor: TagActor): Promise<boolean> {\n const id = requireNonEmpty(tagId, 'tagId');\n const assignments = await this.getEntityTags(entityType, entityId, actor);\n const matches = assignments.filter((assignment) => assignment.tagId === id);\n if (matches.length === 0) return false;\n\n let removed = false;\n for (const assignment of matches) {\n const data = await this.request<{ removeTagAssignment: boolean | null }>(\n `mutation RemoveTagAssignment($id: ID!) { removeTagAssignment(id: $id) }`,\n { id: assignment.id },\n actor\n );\n removed = data.removeTagAssignment === true || removed;\n }\n return removed;\n }\n\n /** Replace the full tag set on an entity (an empty list clears it). */\n async replaceEntityTags(\n entityType: string,\n entityId: string,\n tagIds: readonly string[],\n actor: TagActor\n ): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n const data = await this.request<{ replaceEntityTags: RawTagAssignment[] | null }>(\n `mutation ReplaceEntityTags($entityType: String!, $entityId: ID!, $tagIds: [ID!]!) {\n replaceEntityTags(entityType: $entityType, entityId: $entityId, tagIds: $tagIds) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id, tagIds: uniqueTagIds },\n actor\n );\n return (data.replaceEntityTags ?? []).map(mapTagAssignment);\n }\n\n /**\n * Ids of `entityType` entities carrying the given tags — the server-side half of\n * \"filter this list by tag\". Intersect the ids with the service's own query.\n */\n async findEntityIdsByTags(\n entityType: string,\n tagIds: readonly string[],\n actor: TagActor,\n options: FindEntitiesByTagsOptions = {}\n ): Promise<TaggedEntityPage> {\n this.assertEntityType(entityType);\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n if (uniqueTagIds.length === 0) {\n throw new EntityTagsError('INVALID_INPUT', 'tagIds must contain at least one tag', { field: 'tagIds' });\n }\n const data = await this.request<{\n getEntitiesByTags: {\n entities: Array<{ entityId: string; entityType: string }>;\n total: number;\n hasMore: boolean;\n nextCursor?: string | null;\n } | null;\n }>(\n `query GetEntitiesByTags($tagIds: [ID!]!, $entityType: String, $matchAll: Boolean, $pagination: TagsPaginationInput) {\n getEntitiesByTags(tagIds: $tagIds, entityType: $entityType, matchAll: $matchAll, pagination: $pagination) {\n entities { entityId entityType } total hasMore nextCursor\n }\n }`,\n {\n tagIds: uniqueTagIds,\n entityType,\n matchAll: options.matchAll ?? false,\n pagination: {\n limit: clampLimit(options.limit, ENTITIES_BY_TAGS_LIMIT),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n },\n },\n actor\n );\n const page = data.getEntitiesByTags;\n if (!page) return { entityIds: [], total: 0, hasMore: false, nextCursor: null };\n return {\n // tags-svc already filters by entityType; re-check so a lax upstream never\n // leaks another product's ids into this service's list.\n entityIds: page.entities.filter((entity) => entity.entityType === entityType).map((entity) => entity.entityId),\n total: page.total,\n hasMore: page.hasMore,\n nextCursor: page.nextCursor ?? null,\n };\n }\n\n // ── Workspace tags ────────────────────────────────────────────────────\n\n /** Search assignable tags in the workspace. */\n async searchTags(query: string, actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ searchTags: AvailableTag[] | null }>(\n `query SearchTags($query: String!, $limit: Int) {\n searchTags(query: $query, limit: $limit) { id key label color }\n }`,\n { query: query.trim(), limit: clampLimit(limit, SEARCH_LIMIT) },\n actor\n );\n return data.searchTags ?? [];\n }\n\n /** List assignable tags in the workspace. */\n async getAvailableTags(actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ getTags: { items: AvailableTag[] | null } | null }>(\n `query GetTags($pagination: TagsPaginationInput) {\n getTags(pagination: $pagination) { items { id key label color } }\n }`,\n { pagination: { limit: clampLimit(limit, AVAILABLE_LIMIT) } },\n actor\n );\n return data.getTags?.items ?? [];\n }\n\n /** Create a workspace tag, in the default vocabulary unless `vocabularyId` is given. */\n async createTag(options: CreateTagOptions, actor: TagActor): Promise<AvailableTag> {\n const label = requireNonEmpty(options.label, 'label');\n const vocabularyId =\n options.vocabularyId !== undefined && options.vocabularyId !== null\n ? options.vocabularyId\n : await this.ensureWorkspaceVocabulary(actor);\n\n const data = await this.request<{ createTag: AvailableTag | null }>(\n `mutation CreateTag($input: CreateTagInput!) {\n createTag(input: $input) { id key label color }\n }`,\n {\n input: {\n vocabularyId,\n key: slugifyTagKey(label),\n label,\n color: options.color || undefined,\n },\n },\n actor\n );\n if (!data.createTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no tag', { label });\n }\n return data.createTag;\n }\n\n // ── Vocabularies ──────────────────────────────────────────────────────\n\n /**\n * Resolve the workspace's default vocabulary id, creating the vocabulary on first\n * use. Order: pinned `id` (if it exists in this workspace) → lookup by `key` →\n * create → re-read by key (a concurrent request may have created it first).\n */\n async ensureWorkspaceVocabulary(actor: TagActor, override: Partial<TagVocabularyConfig> = {}): Promise<string> {\n const vocabulary = { ...this.vocabulary, ...override };\n\n if (vocabulary.id) {\n const byId = await this.getVocabularyById(vocabulary.id, actor);\n if (byId?.id) return byId.id;\n }\n\n const byKey = await this.getVocabularyByKey(vocabulary.key, actor);\n if (byKey?.id) return byKey.id;\n\n let createError: unknown = null;\n try {\n const created = await this.createVocabulary(vocabulary, actor);\n if (created?.id) return created.id;\n } catch (error) {\n // Most likely a unique-key race with a concurrent request; the re-read below\n // decides. Kept so the failure is not swallowed when the re-read finds nothing.\n createError = error;\n }\n\n const afterCreate = await this.getVocabularyByKey(vocabulary.key, actor);\n if (afterCreate?.id) return afterCreate.id;\n\n if (createError) throw createError;\n throw new EntityTagsError('UPSTREAM_ERROR', `Failed to resolve tag vocabulary \"${vocabulary.key}\"`, {\n vocabularyKey: vocabulary.key,\n });\n }\n\n async getVocabularyById(id: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabulary: TagVocabularyRef | null }>(\n `query GetVocabulary($id: ID!) { getVocabulary(id: $id) { id key name } }`,\n { id },\n actor\n );\n return data.getVocabulary ?? null;\n }\n\n async getVocabularyByKey(key: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabularyByKey: TagVocabularyRef | null }>(\n `query GetVocabularyByKey($key: String!) { getVocabularyByKey(key: $key) { id key name } }`,\n { key },\n actor\n );\n return data.getVocabularyByKey ?? null;\n }\n\n /** Create a WORKSPACE-scoped, multi-valued, open (custom tags allowed) string vocabulary. */\n async createVocabulary(vocabulary: TagVocabularyConfig, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ createVocabulary: TagVocabularyRef | null }>(\n `mutation CreateVocabulary($input: CreateVocabularyInput!) {\n createVocabulary(input: $input) { id key name }\n }`,\n {\n input: {\n key: requireNonEmpty(vocabulary.key, 'vocabulary.key'),\n name: requireNonEmpty(vocabulary.name, 'vocabulary.name'),\n description: vocabulary.description,\n scope: 'WORKSPACE',\n dataType: 'STRING',\n cardinality: 'MULTIPLE',\n allowCustomTags: true,\n },\n },\n actor\n );\n return data.createVocabulary ?? null;\n }\n\n // ── Transport ─────────────────────────────────────────────────────────\n\n private requireActor(actor: TagActor): TagActor {\n if (!actor.actorId?.trim() || !actor.workspaceId?.trim()) {\n throw new EntityTagsError('MISSING_CONTEXT', 'Tag operations need an authenticated actor and a workspace');\n }\n return actor;\n }\n\n private getClient(): Promise<TagsGatewayClient> {\n if (!this.clientPromise) {\n const option = this.clientOption;\n this.clientPromise = (async (): Promise<TagsGatewayClient> => {\n if (typeof option === 'function') return option();\n if (option) return option;\n // Dynamic import keeps the gateway client (and its JWT/crypto deps) out of\n // the static module graph of `@burdenoff/be-sdk/tags` consumers.\n const gateway = await import('../gateway/client.js');\n if (this.serviceName) {\n return new gateway.GatewayClient({\n layer: 'wspace',\n serviceName: this.serviceName,\n serviceIdentity: this.serviceName,\n });\n }\n return gateway.createGatewayClientFromEnv();\n })();\n // A failed construction (bad env) must not be cached forever.\n this.clientPromise.catch(() => {\n this.clientPromise = null;\n });\n }\n return this.clientPromise;\n }\n\n private async request<T>(query: string, variables: Record<string, unknown>, actor: TagActor): Promise<T> {\n const { actorId, workspaceId, actorType } = this.requireActor(actor);\n const client = await this.getClient();\n const response = await client.internalQuery<T>({\n query,\n variables,\n timeout: this.requestTimeoutMs,\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType || 'user',\n 'x-workspace-id': workspaceId,\n },\n });\n if (response.errors?.length) {\n throw new EntityTagsError(\n 'UPSTREAM_ERROR',\n `wspace-tags-svc error: ${response.errors.map((error) => error.message).join('; ')}`,\n { errors: response.errors }\n );\n }\n if (!response.data) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no data');\n }\n return response.data;\n }\n}\n","/**\n * Entity tags — SDL generator.\n *\n * One fixed SDL fragment cannot be shared: two subgraphs declaring the same\n * non-`@shareable` value type (`EntityTagAssignment`, `AvailableTag`, …) fail\n * Federation composition. {@link buildEntityTagsSdl} therefore emits the whole\n * tag surface under a per-service prefix (names from `./naming.ts`), with a\n * static `@rbac` directive on every root field — the gateway enforces RBAC from\n * the composed supergraph and needs a literal action/resource per field.\n *\n * The SDL references `@rbac`, `JSON`, `DateTime` and the federated\n * `UniversalTag` entity, which the host subgraph already declares (pass\n * `includeUniversalTagStub: true` if it does not declare `UniversalTag` yet).\n */\nimport { EntityTagsError } from './errors.js';\nimport { entityTagsFieldNames, entityTagsTypeNames, type EntityTagsTypeNames } from './naming.js';\n\nconst TYPE_NAME_PATTERN = /^[A-Z]\\w*$/;\nconst RBAC_TOKEN_PATTERN = /^[a-z0-9][a-z0-9:_-]*$/i;\n\n/** The `@rbac` arguments stamped on the generated root fields. */\nexport interface EntityTagsRbacOptions {\n /** RBAC resource the service already gates its entities on, e.g. `workflow`, `agent`. */\n resource: string;\n /** Default `wspace`. */\n scopeType?: string;\n /** Action for the read fields. Default `read`. */\n readAction?: string;\n /** Action for tag/untag/replace. Default `update`. */\n updateAction?: string;\n /** Action for creating a workspace tag. Default `create`. */\n createAction?: string;\n}\n\nexport interface EntityTagsSdlOptions {\n /** PascalCase service prefix, e.g. `Fluidgrids` → `fluidgridsEntityTags`, `FluidgridsTagAssignment`. */\n prefix: string;\n /** Product name used in field descriptions. Defaults to `prefix`. */\n productLabel?: string;\n rbac: EntityTagsRbacOptions;\n /** Types (owned elsewhere in the subgraph) that get a `tagAssignments` field. */\n extendTypes?: readonly string[];\n /** Override generated type names, for services with already-published legacy names. */\n typeNames?: Partial<EntityTagsTypeNames>;\n /** Types the subgraph already declares elsewhere: referenced, not declared. */\n externalTypes?: readonly (keyof EntityTagsTypeNames)[];\n /** Also emit the `…EntitiesByTags` query (server-side filter-by-tag). Default `false`. */\n includeEntitiesByTags?: boolean;\n /** Also declare the non-resolvable `UniversalTag @key(fields: \"id\")` stub. Default `false`. */\n includeUniversalTagStub?: boolean;\n}\n\n/** Non-resolvable stub for the tags-svc-owned `UniversalTag` entity. */\nexport const UNIVERSAL_TAG_STUB_SDL = /* GraphQL */ `\n \"UniversalTag is owned by wspace-tags-svc; only its key is resolvable here.\"\n type UniversalTag @key(fields: \"id\", resolvable: false) {\n id: ID!\n }\n`;\n\nfunction rbacToken(value: string, field: string): string {\n if (!RBAC_TOKEN_PATTERN.test(value)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags rbac.${field} \"${value}\" is not a valid RBAC token`, {\n field,\n value,\n });\n }\n return value;\n}\n\nfunction rbacDirective(action: string, resource: string, scopeType: string): string {\n return `@rbac(action: \"${action}\", resource: \"${resource}\", scopeType: \"${scopeType}\")`;\n}\n\nfunction sanitizeDescription(value: string): string {\n // Config-time text inside a \"...\" description: no quote or backslash may end/escape it.\n return value.replace(/[\"\\\\]/g, \"'\").replace(/\\s+/g, ' ').trim();\n}\n\nexport function buildEntityTagsSdl(options: EntityTagsSdlOptions): string {\n const fields = entityTagsFieldNames(options.prefix);\n const types = entityTagsTypeNames(options.prefix, options.typeNames);\n const external = new Set<keyof EntityTagsTypeNames>(options.externalTypes ?? []);\n const label = sanitizeDescription(options.productLabel ?? options.prefix);\n\n const resource = rbacToken(options.rbac.resource, 'resource');\n const scopeType = rbacToken(options.rbac.scopeType ?? 'wspace', 'scopeType');\n const read = rbacDirective(rbacToken(options.rbac.readAction ?? 'read', 'readAction'), resource, scopeType);\n const update = rbacDirective(rbacToken(options.rbac.updateAction ?? 'update', 'updateAction'), resource, scopeType);\n const create = rbacDirective(rbacToken(options.rbac.createAction ?? 'create', 'createAction'), resource, scopeType);\n\n const extendTypes = [...new Set(options.extendTypes ?? [])];\n for (const typeName of extendTypes) {\n if (!TYPE_NAME_PATTERN.test(typeName)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Cannot extend \"${typeName}\": not a valid type name`, {\n typeName,\n });\n }\n }\n\n const blocks: string[] = [];\n const emitType = (role: keyof EntityTagsTypeNames, sdl: string): void => {\n if (!external.has(role)) blocks.push(sdl);\n };\n\n if (options.includeUniversalTagStub) blocks.push(UNIVERSAL_TAG_STUB_SDL.trim());\n\n emitType(\n 'getEntityTagsInput',\n `input ${types.getEntityTagsInput} {\n entityType: String!\n entityId: ID!\n}`\n );\n emitType(\n 'tagEntityInput',\n `input ${types.tagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n \"AssignmentSource (MANUAL, AUTOMATIC, IMPORTED, ...). Defaults to the service default.\"\n source: String\n metadata: JSON\n}`\n );\n emitType(\n 'untagEntityInput',\n `input ${types.untagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n}`\n );\n emitType(\n 'replaceEntityTagsInput',\n `input ${types.replaceEntityTagsInput} {\n entityType: String!\n entityId: ID!\n tagIds: [ID!]!\n}`\n );\n emitType(\n 'createTagInput',\n `input ${types.createTagInput} {\n \"Optional. When omitted the tag goes to the workspace's default ${label} vocabulary (created on first use).\"\n vocabularyId: ID\n label: String!\n color: String\n}`\n );\n emitType(\n 'tagInfo',\n `\"Inline (non-federated) tag projection, so clients render labels without a federated round-trip.\"\ntype ${types.tagInfo} {\n id: ID!\n key: String\n label: String\n color: String\n}`\n );\n emitType(\n 'tagAssignment',\n `\"A tag assigned to a ${label} entity.\"\ntype ${types.tagAssignment} {\n id: ID!\n tagId: ID!\n \"Federated UniversalTag reference (owned by wspace-tags-svc). Prefer tagInfo for label/colour.\"\n tag: UniversalTag\n \"Inline projection of the tag (key/label/colour).\"\n tagInfo: ${types.tagInfo}\n entityType: String!\n entityId: ID!\n source: String!\n assignedBy: ID\n assignedAt: DateTime\n validFrom: DateTime\n validTo: DateTime\n metadata: JSON\n}`\n );\n emitType(\n 'availableTag',\n `\"An assignable workspace tag.\"\ntype ${types.availableTag} {\n id: ID!\n key: String!\n label: String!\n color: String\n}`\n );\n\n if (options.includeEntitiesByTags) {\n emitType(\n 'entitiesByTagsInput',\n `input ${types.entitiesByTagsInput} {\n entityType: String!\n tagIds: [ID!]!\n \"true = entity must carry every tag; false (default) = any of them.\"\n matchAll: Boolean\n limit: Int\n cursor: String\n}`\n );\n emitType(\n 'taggedEntityPage',\n `\"Ids of entities carrying the requested tags.\"\ntype ${types.taggedEntityPage} {\n entityIds: [ID!]!\n total: Int!\n hasMore: Boolean!\n nextCursor: String\n}`\n );\n }\n\n const queryFields = [\n ` \"Tags currently assigned to a ${label} entity\"\n ${fields.entityTags}(input: ${types.getEntityTagsInput}!): [${types.tagAssignment}!]! ${read}`,\n ` \"Search assignable tags in the workspace\"\n ${fields.searchTags}(query: String!, limit: Int): [${types.availableTag}!]! ${read}`,\n ` \"List assignable tags in the workspace\"\n ${fields.availableTags}(limit: Int): [${types.availableTag}!]! ${read}`,\n ];\n if (options.includeEntitiesByTags) {\n queryFields.push(` \"Ids of ${label} entities carrying the given tags (filter-by-tag)\"\n ${fields.entitiesByTags}(input: ${types.entitiesByTagsInput}!): ${types.taggedEntityPage}! ${read}`);\n }\n blocks.push(`extend type Query {\\n${queryFields.join('\\n\\n')}\\n}`);\n\n blocks.push(`extend type Mutation {\n \"Assign a tag to a ${label} entity\"\n ${fields.tagEntity}(input: ${types.tagEntityInput}!): ${types.tagAssignment}! ${update}\n\n \"Remove a tag from a ${label} entity\"\n ${fields.untagEntity}(input: ${types.untagEntityInput}!): Boolean! ${update}\n\n \"Replace the full tag set on a ${label} entity\"\n ${fields.replaceEntityTags}(input: ${types.replaceEntityTagsInput}!): [${types.tagAssignment}!]! ${update}\n\n \"Create a new assignable tag (inline creation from a picker)\"\n ${fields.createTag}(input: ${types.createTagInput}!): ${types.availableTag}! ${create}\n}`);\n\n for (const typeName of extendTypes) {\n blocks.push(`extend type ${typeName} {\n \"Structured tag assignments (wspace-tags-svc).\"\n tagAssignments: [${types.tagAssignment}!]!\n}`);\n }\n\n return `${blocks.join('\\n\\n')}\\n`;\n}\n","/**\n * Entity tags — resolver factory.\n *\n * Builds the Query / Mutation / `tagAssignments` resolvers that match the SDL\n * from {@link buildEntityTagsSdl} for the same `prefix` (both derive names from\n * `./naming.ts`). The service supplies only what differs: how to read the actor\n * off its context, which GraphQL types map to which entity types, how to map\n * errors onto its i18n errors, and optional ownership/audit hooks.\n *\n * @example\n * ```ts\n * import { GraphQLError } from 'graphql';\n * import { buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const { Query, Mutation, types } = createEntityTagResolvers({\n * prefix: 'Fluidgrids',\n * adapter: entityTags,\n * entities: {\n * WorkflowDefinition: { entityType: 'FLUIDGRIDS_WORKFLOW', entityId: (p) => String(p.workflowKey ?? '') },\n * WorkflowRun: { entityType: 'FLUIDGRIDS_RUN' },\n * },\n * authorizeEntity: async ({ entityType, entityId, actor }, ctx) => {\n * const owned = await entityExistsForActor(ctx.prisma, entityType, entityId, actor);\n * if (!owned) {\n * throw new GraphQLError('Not found', { extensions: { code: 'NOT_FOUND' } });\n * }\n * },\n * mapError: (error, ctx) => workflowError(`tags.errors.${error.code}`, error.graphqlCode, ctx, error.details),\n * });\n * ```\n */\nimport { GraphQLError } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { TagsGatewayAdapter } from './adapter.js';\nimport { EntityTagsError, isEntityTagsError } from './errors.js';\nimport { entityTagsFieldNames } from './naming.js';\nimport type { AvailableTag, EntityTagAssignment, TagActor, TagActorType, TaggedEntityPage } from './types.js';\nimport { TAG_ACTOR_TYPES } from './types.js';\n\n/** Maps a GraphQL object type onto the entity type and id its tags are stored under. */\nexport interface EntityTagBinding {\n entityType: string;\n /**\n * Entity id for a parent object. Defaults to `parent.id`. Use a stable logical id\n * when rows are versioned (FluidGrids tags `workflowKey`, not the per-version row id).\n */\n entityId?: (parent: Record<string, unknown>) => string | null | undefined;\n}\n\nexport type EntityTagOperation = 'tag' | 'untag' | 'replace' | 'createTag';\n\n/** Emitted after a successful write, for audit/activity logging. */\nexport interface EntityTagMutationEvent {\n operation: EntityTagOperation;\n /** Root field name, e.g. `tagFluidgridsEntity`. */\n fieldName: string;\n actor: TagActor;\n entityType?: string;\n entityId?: string;\n tagId?: string;\n tagIds?: string[];\n source?: string;\n /** For `createTag`. */\n tag?: AvailableTag;\n vocabularyId?: string;\n}\n\n/** Passed to `authorizeEntity` before any entity-addressed operation. */\nexport interface EntityTagAccessCheck {\n entityType: string;\n entityId: string;\n access: 'read' | 'write';\n actor: TagActor;\n}\n\ninterface CreateEntityTagResolversBaseOptions<TContext> {\n /** Same prefix as passed to `buildEntityTagsSdl`. */\n prefix: string;\n adapter: TagsGatewayAdapter;\n /** GraphQL type name → binding, for the `tagAssignments` field on each extended type. */\n entities?: Readonly<Record<string, EntityTagBinding>>;\n /**\n * Reads the caller off the request context. Default: be-sdk server context\n * (`context.actor.{id,type}`, `context.workspace.id`), falling back to flat\n * `context.actorId` / `context.workspaceId`.\n */\n getActor?: (context: TContext) => TagActor;\n /** Called after each successful write. Failures are logged, never surfaced. */\n onMutation?: (event: EntityTagMutationEvent, context: TContext) => void | Promise<void>;\n /** Map an adapter error onto the service's own (i18n) GraphQL error. */\n mapError?: (error: EntityTagsError, context: TContext) => Error;\n /** Must match `includeEntitiesByTags` on the SDL. Default `false`. */\n includeEntitiesByTags?: boolean;\n}\n\nexport type CreateEntityTagResolversOptions<TContext> = CreateEntityTagResolversBaseOptions<TContext> &\n (\n | {\n /**\n * Required object-level ownership/ACL check for entity-addressed tag\n * operations (throw to deny). Confirm the entity exists in the caller's\n * workspace and is reachable by the caller before tags are read or\n * written for an arbitrary `entityId`; throw NOT_FOUND, never FORBIDDEN.\n */\n authorizeEntity: (check: EntityTagAccessCheck, context: TContext) => void | Promise<void>;\n /** Do not set when `authorizeEntity` is provided. */\n unsafeAllowUncheckedEntityIds?: false;\n }\n | {\n authorizeEntity?: undefined;\n /**\n * Explicit opt-out for tests or services whose entities genuinely have\n * no object-level authorization. Emits a loud startup warning and skips\n * entity ownership verification.\n */\n unsafeAllowUncheckedEntityIds: true;\n }\n );\n\ntype Resolver<TArgs, TResult, TContext> = (parent: unknown, args: TArgs, context: TContext) => Promise<TResult>;\n\ntype TagAssignmentsResolver<TContext> = (\n parent: Record<string, unknown>,\n args: unknown,\n context: TContext\n) => Promise<EntityTagAssignment[]>;\n\ninterface EntityRefInput {\n entityType: string;\n entityId: string;\n}\n\nexport interface EntityTagResolvers<TContext> {\n Query: Record<string, Resolver<never, unknown, TContext>>;\n Mutation: Record<string, Resolver<never, unknown, TContext>>;\n /** `{ [GraphQLTypeName]: { tagAssignments } }`, ready to spread into the resolver map. */\n types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }>;\n}\n\nfunction readRecord(value: unknown, key: string): unknown {\n if (value === null || typeof value !== 'object') return undefined;\n return (value as Record<string, unknown>)[key];\n}\n\nfunction readString(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction toActorType(value: unknown): TagActorType {\n return TAG_ACTOR_TYPES.find((candidate) => candidate === value) ?? 'user';\n}\n\n/** Default actor reader for the be-sdk server context shape. */\nexport function defaultTagActor(context: unknown): TagActor {\n const actor = readRecord(context, 'actor');\n const workspace = readRecord(context, 'workspace');\n return {\n actorId: readString(readRecord(actor, 'id')) || readString(readRecord(context, 'actorId')),\n actorType: toActorType(readRecord(actor, 'type') ?? readRecord(context, 'actorType')),\n workspaceId: readString(readRecord(workspace, 'id')) || readString(readRecord(context, 'workspaceId')),\n };\n}\n\nfunction defaultMapError(error: EntityTagsError): Error {\n if (error.code === 'UPSTREAM_ERROR' || error.code === 'CONFIGURATION_ERROR') {\n // Upstream payloads can carry internal detail; log it, return a generic message.\n logger.error('[be-sdk/tags] Tag operation failed', { code: error.code, message: error.message });\n return new GraphQLError('Tag operation failed', { extensions: { code: error.graphqlCode } });\n }\n return new GraphQLError(error.message, { extensions: { code: error.graphqlCode, reason: error.code } });\n}\n\nexport function createEntityTagResolvers<TContext>(\n options: CreateEntityTagResolversOptions<TContext>\n): EntityTagResolvers<TContext> {\n const { adapter, prefix } = options;\n const fields = entityTagsFieldNames(prefix);\n const getActor = options.getActor ?? ((context: TContext) => defaultTagActor(context));\n const mapError = options.mapError ?? ((error: EntityTagsError) => defaultMapError(error));\n\n if (typeof options.authorizeEntity !== 'function') {\n if (options.unsafeAllowUncheckedEntityIds === true) {\n logger.warn(\n '[be-sdk/tags] createEntityTagResolvers initialized with unsafeAllowUncheckedEntityIds=true — entity-addressed tag resolvers will NOT verify entity existence or object-level authorization',\n { prefix }\n );\n } else {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n 'authorizeEntity is required in createEntityTagResolvers (pass unsafeAllowUncheckedEntityIds: true only if entity IDs are intentionally unchecked)',\n { prefix }\n );\n }\n }\n\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n if (!adapter.isValidEntityType(binding.entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `${typeName} is bound to entity type \"${binding.entityType}\", which the adapter does not register`,\n { typeName, entityType: binding.entityType }\n );\n }\n }\n\n const guard = async <T>(context: TContext, run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n if (isEntityTagsError(error)) throw mapError(error, context);\n throw error;\n }\n };\n\n const authorize = async (\n input: EntityRefInput,\n access: EntityTagAccessCheck['access'],\n actor: TagActor,\n context: TContext\n ): Promise<void> => {\n adapter.assertEntityType(input.entityType);\n if (!input.entityId?.trim()) {\n throw new EntityTagsError('INVALID_INPUT', 'entityId is required', { field: 'entityId' });\n }\n if (options.authorizeEntity) {\n await options.authorizeEntity({ entityType: input.entityType, entityId: input.entityId, access, actor }, context);\n }\n };\n\n const notify = async (event: EntityTagMutationEvent, context: TContext): Promise<void> => {\n if (!options.onMutation) return;\n try {\n await options.onMutation(event, context);\n } catch (error) {\n logger.warn('[be-sdk/tags] onMutation hook failed', {\n fieldName: event.fieldName,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n const Query: Record<string, Resolver<never, unknown, TContext>> = {};\n const Mutation: Record<string, Resolver<never, unknown, TContext>> = {};\n\n const entityTags: Resolver<{ input: EntityRefInput }, EntityTagAssignment[], TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'read', actor, context);\n return adapter.getEntityTags(input.entityType, input.entityId, actor);\n });\n Query[fields.entityTags] = entityTags;\n\n const searchTags: Resolver<{ query: string; limit?: number | null }, AvailableTag[], TContext> = (\n _parent,\n { query, limit },\n context\n ) => guard(context, () => adapter.searchTags(query, getActor(context), limit));\n Query[fields.searchTags] = searchTags;\n\n const availableTags: Resolver<{ limit?: number | null }, AvailableTag[], TContext> = (_parent, { limit }, context) =>\n guard(context, () => adapter.getAvailableTags(getActor(context), limit));\n Query[fields.availableTags] = availableTags;\n\n if (options.includeEntitiesByTags) {\n const entitiesByTags: Resolver<\n {\n input: {\n entityType: string;\n tagIds: string[];\n matchAll?: boolean | null;\n limit?: number | null;\n cursor?: string | null;\n };\n },\n TaggedEntityPage,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, () =>\n adapter.findEntityIdsByTags(input.entityType, input.tagIds, getActor(context), {\n matchAll: input.matchAll ?? false,\n limit: input.limit,\n cursor: input.cursor,\n })\n );\n Query[fields.entitiesByTags] = entitiesByTags;\n }\n\n const tagEntity: Resolver<\n { input: EntityRefInput & { tagId: string; source?: string | null; metadata?: Record<string, unknown> | null } },\n EntityTagAssignment,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignment = await adapter.tagEntity(\n input.entityType,\n input.entityId,\n { tagId: input.tagId, source: input.source, metadata: input.metadata },\n actor\n );\n await notify(\n {\n operation: 'tag',\n fieldName: fields.tagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n source: assignment.source,\n },\n context\n );\n return assignment;\n });\n Mutation[fields.tagEntity] = tagEntity;\n\n const untagEntity: Resolver<{ input: EntityRefInput & { tagId: string } }, boolean, TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const removed = await adapter.untagEntity(input.entityType, input.entityId, input.tagId, actor);\n if (removed) {\n await notify(\n {\n operation: 'untag',\n fieldName: fields.untagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n },\n context\n );\n }\n return removed;\n });\n Mutation[fields.untagEntity] = untagEntity;\n\n const replaceEntityTags: Resolver<\n { input: EntityRefInput & { tagIds: string[] } },\n EntityTagAssignment[],\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignments = await adapter.replaceEntityTags(input.entityType, input.entityId, input.tagIds, actor);\n await notify(\n {\n operation: 'replace',\n fieldName: fields.replaceEntityTags,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagIds: [...new Set(input.tagIds)],\n },\n context\n );\n return assignments;\n });\n Mutation[fields.replaceEntityTags] = replaceEntityTags;\n\n const createTag: Resolver<\n { input: { vocabularyId?: string | null; label: string; color?: string | null } },\n AvailableTag,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n const vocabularyId =\n input.vocabularyId !== undefined && input.vocabularyId !== null\n ? input.vocabularyId\n : await adapter.ensureWorkspaceVocabulary(actor);\n const tag = await adapter.createTag({ label: input.label, color: input.color, vocabularyId }, actor);\n await notify({ operation: 'createTag', fieldName: fields.createTag, actor, tag, vocabularyId }, context);\n return tag;\n });\n Mutation[fields.createTag] = createTag;\n\n const types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }> = {};\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n const selectId = binding.entityId ?? ((parent: Record<string, unknown>) => readString(parent['id']));\n types[typeName] = {\n tagAssignments: async (parent, _args, context) => {\n const entityId = selectId(parent);\n if (!entityId) return [];\n try {\n return await adapter.getEntityTags(binding.entityType, entityId, getActor(context));\n } catch (error) {\n // The field is non-nullable decoration: a tags-svc outage must never fail\n // the parent query (a workflow list, a run page, …).\n logger.warn('[be-sdk/tags] Failed to resolve tagAssignments', {\n typeName,\n entityType: binding.entityType,\n entityId,\n error: error instanceof Error ? error.message : String(error),\n });\n return [];\n }\n },\n };\n }\n\n return { Query, Mutation, types };\n}\n","/**\n * @burdenoff/be-sdk/tags\n *\n * Shared \"tag my entities\" surface for product services, backed by\n * wspace-tags-svc through the internal workspace gateway:\n *\n * - {@link TagsGatewayAdapter} — the configurable adapter (entity types, default\n * vocabulary, default source) that replaces the per-service EntityTagAdapter copies.\n * - {@link buildEntityTagsSdl} — the per-service, prefixed SDL (unique type names so\n * subgraphs never collide in composition; static `@rbac` on every root field).\n * - {@link createEntityTagResolvers} — the matching Query / Mutation /\n * `tagAssignments` resolvers, with ownership, audit and error-mapping hooks.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter, buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const adapter = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n * export const typeDefs = buildEntityTagsSdl({\n * prefix: 'Fluidgrids',\n * productLabel: 'FluidGrids',\n * rbac: { resource: 'workflow' },\n * extendTypes: ['WorkflowDefinition', 'WorkflowRun'],\n * });\n * export const resolvers = createEntityTagResolvers({\n * prefix: 'Fluidgrids',\n * adapter,\n * entities: { … },\n * authorizeEntity: async ({ entityType, entityId, actor }, ctx) => {\n * if (!(await entityExistsForActor(ctx.prisma, entityType, entityId, actor))) {\n * throw new GraphQLError('Not found', { extensions: { code: 'NOT_FOUND' } });\n * }\n * },\n * });\n * ```\n */\n\nexport {\n TAG_ACTOR_TYPES,\n TAG_ASSIGNMENT_SOURCES,\n type AvailableTag,\n type CreateTagOptions,\n type EntityTagAssignment,\n type EntityTagInfo,\n type FindEntitiesByTagsOptions,\n type RawTagAssignment,\n type TagActor,\n type TagActorType,\n type TagAssignmentSource,\n type TagEntityOptions,\n type TaggedEntityPage,\n type TagsGatewayClient,\n type TagVocabularyConfig,\n type TagVocabularyRef,\n} from './types.js';\n\nexport { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, isEntityTagsError, type EntityTagsErrorCode } from './errors.js';\n\nexport {\n assertTagPrefix,\n entityTagsFieldNames,\n entityTagsTypeNames,\n type EntityTagsFieldNames,\n type EntityTagsTypeNames,\n} from './naming.js';\n\nexport { TagsGatewayAdapter, mapTagAssignment, slugifyTagKey, type TagsGatewayAdapterOptions } from './adapter.js';\n\nexport {\n UNIVERSAL_TAG_STUB_SDL,\n buildEntityTagsSdl,\n type EntityTagsRbacOptions,\n type EntityTagsSdlOptions,\n} from './sdl.js';\n\nexport {\n createEntityTagResolvers,\n defaultTagActor,\n type CreateEntityTagResolversOptions,\n type EntityTagAccessCheck,\n type EntityTagBinding,\n type EntityTagMutationEvent,\n type EntityTagOperation,\n type EntityTagResolvers,\n} from './res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AAI,CAAC,UAAU,OAAO,CAAC;GACvB,IAAI;IACF,OAAO,MAAM,QAAQ,cAAc,QAAQ,YAAY,UAAU,SAAS,OAAO,CAAC;GACpF,SAAS,OAAO;IAGd,OAAO,KAAK,kDAAkD;KAC5D;KACA,YAAY,QAAQ;KACpB;KACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,CAAC;IACD,OAAO,CAAC;GACV;EACF,EACF;CACF;CAEA,OAAO;EAAE;EAAO;EAAU;CAAM;AAClC"}
@@ -1,5 +1,5 @@
1
1
  import { r as Logger } from "../index-KlrnELrN.js";
2
- import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-479i3w77.js";
2
+ import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-BgOU0pxB.js";
3
3
  interface TelemetryIdGenerator {
4
4
  generateTraceId(): string;
5
5
  generateSpanId(): string;
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-ad2WFvuA.js";
2
2
  import { a as logger, s as redactSensitiveFields, t as Logger } from "../logger-B6rCpb7D.js";
3
- import { n as initializeInstrumentation, o as setupInstrumentation, w as setActiveTelemetryLogger } from "../instrumentation-xkkmDgJ0.js";
3
+ import { T as setActiveTelemetryLogger, n as initializeInstrumentation, o as setupInstrumentation } from "../instrumentation-C738xDj8.js";
4
4
  import { a as resolveCollectorLayer, i as defaultCollectorTracesEndpoint, n as OTLP_HTTP_PORT, r as defaultCollectorEndpoint, t as COLLECTOR_SERVICE } from "../collector-endpoint-iyQYeI50.js";
5
5
  import { t as collectPromDefaultMetrics } from "../bun-runtime-metrics-CPy5D6NT.js";
6
6
 
@@ -1,4 +1,4 @@
1
- import { n as PrismaClientBase, r as PrismaClientConstructorOptions } from "./client-BgAEvDC2.js";
1
+ import { n as PrismaClientBase, r as PrismaClientConstructorOptions } from "./client-NknQrWsP.js";
2
2
  import { o as WorkspaceExtensionConfig } from "./workspace-extension-DTFTdGVF.js";
3
3
  import { r as I18nContext, s as LocaleCode } from "./types-DgaQqvxo.js";
4
4
  import { o as AssistantSessionAttribution } from "./assistant-session-DA5ZKJOr.js";
@@ -203,6 +203,8 @@ interface ServerConfig {
203
203
  loginEndpoints?: string[];
204
204
  enableCSRF?: boolean;
205
205
  enableSessionSecurity?: boolean;
206
+ maxBodyBytes?: number;
207
+ maxRequestBodySize?: number;
206
208
  i18n?: ServerI18nConfig;
207
209
  workspaceGuard?: {
208
210
  enabled?: boolean;
@@ -224,6 +226,7 @@ interface RESTEndpoint {
224
226
  path: string;
225
227
  handler: (request: Request, context: GraphQLContext, rawBody?: string) => Promise<unknown>;
226
228
  rawBody?: boolean;
229
+ maxBodyBytes?: number;
227
230
  }
228
231
  type PrismaClientConstructor<T extends PrismaClientBase = PrismaClientBase> = new (options: PrismaClientConstructorOptions) => T;
229
232
  interface YogaPlugin {
@@ -266,6 +269,7 @@ interface ElysiaLikeServer {
266
269
  listen(options: {
267
270
  port: number;
268
271
  hostname?: string;
272
+ maxRequestBodySize?: number;
269
273
  }): ElysiaLikeServer;
270
274
  use(plugin: unknown): ElysiaLikeServer;
271
275
  all(path: string, handler: (ctx: {
@@ -1,2 +1,2 @@
1
- import { A as isValidUrl, C as isValidHexColor, D as isValidRegexPattern, E as isValidPhone, O as isValidSlug, S as isValidEmail, T as isValidJSON, _ as unique, a as generateUUID, b as isStringLengthValid, c as isTokenExpired, d as pick, f as retry, g as truncate, h as throttle, i as formatBytes, k as isValidUUID, l as omit, m as sleep, n as debounce, o as groupBy, p as sanitizeForLog, r as deepMerge, t as chunk, u as parseJWT, v as compileValidatedPattern, w as isValidIPv4, x as isValidBase64, y as isNumberInRange } from "../index-FKohsiex.js";
2
- export { chunk, compileValidatedPattern, debounce, deepMerge, formatBytes, generateUUID, groupBy, isNumberInRange, isStringLengthValid, isTokenExpired, isValidBase64, isValidEmail, isValidHexColor, isValidIPv4, isValidJSON, isValidPhone, isValidRegexPattern, isValidSlug, isValidUUID, isValidUrl, omit, parseJWT, pick, retry, sanitizeForLog, sleep, throttle, truncate, unique };
1
+ import { A as isValidUUID, C as isValidEmail, D as isValidPhone, E as isValidJSON, O as isValidRegexPattern, S as isValidBase64, T as isValidIPv4, _ as truncate, a as generateUUID, b as isNumberInRange, c as isTokenExpired, d as parseJWT, f as pick, g as throttle, h as sleep, i as formatBytes, j as isValidUrl, k as isValidSlug, l as isTokenExpiredUnverified, m as sanitizeForLog, n as debounce, o as groupBy, p as retry, r as deepMerge, t as chunk, u as omit, v as unique, w as isValidHexColor, x as isStringLengthValid, y as compileValidatedPattern } from "../index-BrRQe24P.js";
2
+ export { chunk, compileValidatedPattern, debounce, deepMerge, formatBytes, generateUUID, groupBy, isNumberInRange, isStringLengthValid, isTokenExpired, isTokenExpiredUnverified, isValidBase64, isValidEmail, isValidHexColor, isValidIPv4, isValidJSON, isValidPhone, isValidRegexPattern, isValidSlug, isValidUUID, isValidUrl, omit, parseJWT, pick, retry, sanitizeForLog, sleep, throttle, truncate, unique };
@@ -1,4 +1,4 @@
1
- import { A as isValidUrl, C as isValidHexColor, D as isValidRegexPattern, E as isValidPhone, O as isValidSlug, S as isValidEmail, T as isValidJSON, a as generateUUID, b as isStringLengthValid, c as omit, d as retry, f as sanitizeForLog, g as unique, h as truncate, i as formatBytes, k as isValidUUID, l as parseJWT, m as throttle, n as debounce, o as groupBy, p as sleep, r as deepMerge, s as isTokenExpired, t as chunk, u as pick, v as compileValidatedPattern, w as isValidIPv4, x as isValidBase64, y as isNumberInRange } from "../utils-DL85Tnbn.js";
1
+ import { A as isValidUUID, C as isValidEmail, D as isValidPhone, E as isValidJSON, O as isValidRegexPattern, S as isValidBase64, T as isValidIPv4, _ as unique, a as generateUUID, b as isNumberInRange, c as isTokenExpiredUnverified, d as pick, f as retry, g as truncate, h as throttle, i as formatBytes, j as isValidUrl, k as isValidSlug, l as omit, m as sleep, n as debounce, o as groupBy, p as sanitizeForLog, r as deepMerge, s as isTokenExpired, t as chunk, u as parseJWT, w as isValidHexColor, x as isStringLengthValid, y as compileValidatedPattern } from "../utils-DpW6K_iB.js";
2
2
 
3
- export { chunk, compileValidatedPattern, debounce, deepMerge, formatBytes, generateUUID, groupBy, isNumberInRange, isStringLengthValid, isTokenExpired, isValidBase64, isValidEmail, isValidHexColor, isValidIPv4, isValidJSON, isValidPhone, isValidRegexPattern, isValidSlug, isValidUUID, isValidUrl, omit, parseJWT, pick, retry, sanitizeForLog, sleep, throttle, truncate, unique };
3
+ export { chunk, compileValidatedPattern, debounce, deepMerge, formatBytes, generateUUID, groupBy, isNumberInRange, isStringLengthValid, isTokenExpired, isTokenExpiredUnverified, isValidBase64, isValidEmail, isValidHexColor, isValidIPv4, isValidJSON, isValidPhone, isValidRegexPattern, isValidSlug, isValidUUID, isValidUrl, omit, parseJWT, pick, retry, sanitizeForLog, sleep, throttle, truncate, unique };
4
4
  //# sourceMappingURL=index.js.map
@@ -249,6 +249,7 @@ var utils_exports = /* @__PURE__ */ __exportAll({
249
249
  isNumberInRange: () => isNumberInRange,
250
250
  isStringLengthValid: () => isStringLengthValid,
251
251
  isTokenExpired: () => isTokenExpired,
252
+ isTokenExpiredUnverified: () => isTokenExpiredUnverified,
252
253
  isValidBase64: () => isValidBase64,
253
254
  isValidEmail: () => isValidEmail,
254
255
  isValidHexColor: () => isValidHexColor,
@@ -401,7 +402,10 @@ function throttle(fn, delay) {
401
402
  };
402
403
  }
403
404
  /**
404
- * Parse JWT token (without verification)
405
+ * Parse JWT token payload WITHOUT cryptographic signature verification.
406
+ *
407
+ * SECURITY: Do not trust decoded claims for authentication or authorization
408
+ * decisions; always verify the token signature first.
405
409
  */
406
410
  function parseJWT(token) {
407
411
  try {
@@ -409,22 +413,35 @@ function parseJWT(token) {
409
413
  if (parts.length !== 3) return null;
410
414
  const payload = parts[1];
411
415
  if (!payload) return null;
412
- const decoded = Buffer.from(payload, "base64").toString("utf8");
416
+ const decoded = Buffer.from(payload, "base64url").toString("utf8");
413
417
  return JSON.parse(decoded);
414
418
  } catch {
415
419
  return null;
416
420
  }
417
421
  }
418
422
  /**
419
- * Check if JWT token is expired
423
+ * Inspect whether a JWT's `exp` claim is in the past WITHOUT verifying the
424
+ * cryptographic signature, issuer, audience, or revocation state.
425
+ *
426
+ * SECURITY: Expiry inspection alone NEVER establishes token authenticity and
427
+ * MUST NOT be used as an authentication or authorization predicate.
420
428
  */
421
- function isTokenExpired(token) {
429
+ function isTokenExpiredUnverified(token) {
422
430
  const payload = parseJWT(token);
423
- if (!payload || typeof payload["exp"] !== "number") return true;
431
+ if (!payload || typeof payload["exp"] !== "number" || !Number.isFinite(payload["exp"])) return true;
424
432
  const now = Math.floor(Date.now() / 1e3);
425
433
  return payload["exp"] < now;
426
434
  }
427
435
  /**
436
+ * Check if a JWT's unverified `exp` claim is expired.
437
+ *
438
+ * @deprecated Use {@link isTokenExpiredUnverified} so call sites explicitly
439
+ * acknowledge that this helper does NOT verify the token signature (BOFF-15985).
440
+ */
441
+ function isTokenExpired(token) {
442
+ return isTokenExpiredUnverified(token);
443
+ }
444
+ /**
428
445
  * Format bytes to human readable string
429
446
  */
430
447
  function formatBytes(bytes, decimals = 2) {
@@ -496,5 +513,5 @@ function omit(obj, keys) {
496
513
  return result;
497
514
  }
498
515
 
499
- export { isValidUrl as A, isValidHexColor as C, isValidRegexPattern as D, isValidPhone as E, isValidSlug as O, isValidEmail as S, isValidJSON as T, utils_exports as _, generateUUID as a, isStringLengthValid as b, omit as c, retry as d, sanitizeForLog as f, unique as g, truncate as h, formatBytes as i, isValidUUID as k, parseJWT as l, throttle as m, debounce as n, groupBy as o, sleep as p, deepMerge as r, isTokenExpired as s, chunk as t, pick as u, compileValidatedPattern as v, isValidIPv4 as w, isValidBase64 as x, isNumberInRange as y };
500
- //# sourceMappingURL=utils-DL85Tnbn.js.map
516
+ export { isValidUUID as A, isValidEmail as C, isValidPhone as D, isValidJSON as E, isValidRegexPattern as O, isValidBase64 as S, isValidIPv4 as T, unique as _, generateUUID as a, isNumberInRange as b, isTokenExpiredUnverified as c, pick as d, retry as f, truncate as g, throttle as h, formatBytes as i, isValidUrl as j, isValidSlug as k, omit as l, sleep as m, debounce as n, groupBy as o, sanitizeForLog as p, deepMerge as r, isTokenExpired as s, chunk as t, parseJWT as u, utils_exports as v, isValidHexColor as w, isStringLengthValid as x, compileValidatedPattern as y };
517
+ //# sourceMappingURL=utils-DpW6K_iB.js.map