@ixo/editor 3.2.0 → 3.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-3EZI42YS.mjs → chunk-F2JSGDES.mjs} +577 -570
- package/dist/chunk-F2JSGDES.mjs.map +1 -0
- package/dist/{chunk-BAW3ML7X.mjs → chunk-IQX6H7AK.mjs} +2 -2
- package/dist/{chunk-3MI2QQYH.mjs → chunk-ZCRLP7QH.mjs} +572 -510
- package/dist/chunk-ZCRLP7QH.mjs.map +1 -0
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.mjs +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +3 -3
- package/dist/mantine/index.mjs +2 -2
- package/dist/{setup-Cbd3tcfL.d.ts → setup-B0la8n04.d.ts} +20 -17
- package/package.json +1 -1
- package/dist/chunk-3EZI42YS.mjs.map +0 -1
- package/dist/chunk-3MI2QQYH.mjs.map +0 -1
- /package/dist/{chunk-BAW3ML7X.mjs.map → chunk-IQX6H7AK.mjs.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/lib/actionRegistry/registry.ts","../src/core/lib/actionRegistry/canMapping.ts","../src/core/lib/actionRegistry/adapters.ts","../src/core/lib/matrixDm.ts","../src/core/lib/actionRegistry/diffRegistry.ts","../src/core/lib/actionRegistry/actions/httpRequest.ts","../src/core/lib/actionRegistry/actions/emailSend.ts","../src/core/lib/actionRegistry/actions/humanCheckbox.ts","../src/core/lib/actionRegistry/actions/humanForm.ts","../src/core/lib/actionRegistry/actions/notificationPush.ts","../src/core/lib/actionRegistry/actions/bid/bid.ts","../src/core/lib/actionRegistry/actions/evaluateBid/evaluateBid.ts","../src/core/lib/actionRegistry/actions/claim/claim.ts","../src/core/lib/actionRegistry/actions/evaluateClaim/evaluateClaim.ts","../src/core/lib/actionRegistry/actions/proposalCreate.ts","../src/core/lib/actionRegistry/actions/proposalVote.ts","../src/core/lib/actionRegistry/actions/protocolSelect.ts","../src/mantine/blocks/domainCreator/utils/buildVerifiableCredential.ts","../src/mantine/blocks/domainCreatorSign/utils/buildLinkedEntityResource.ts","../src/core/lib/actionRegistry/actions/domainSign.ts","../src/mantine/blocks/domainCreator/utils/transformSurveyToCredentialSubject.ts","../src/mantine/blocks/domainCreator/utils/extractSurveyAnswersTemplate.ts","../src/core/lib/actionRegistry/actions/domainCreate.ts","../src/core/lib/actionRegistry/actions/oracle.ts","../src/core/lib/actionRegistry/actions/credentialStore.ts","../src/core/lib/actionRegistry/actions/payment.ts","../src/core/lib/actionRegistry/actions/matrixDm.ts","../src/core/lib/actionRegistry/actions/bid/bid.diff.ts","../src/core/lib/actionRegistry/actions/evaluateBid/evaluateBid.diff.ts","../src/core/lib/actionRegistry/actions/claim/claim.diff.ts","../src/core/lib/actionRegistry/actions/evaluateClaim/evaluateClaim.diff.ts","../src/core/lib/ucanDelegationStore.ts","../src/core/lib/invocationStore.ts","../src/core/lib/flowEngine/utils.ts","../src/core/lib/flowEngine/runtime.ts","../src/core/lib/flowEngine/activation.ts","../src/core/lib/flowEngine/versionManifest.ts","../src/core/lib/flowEngine/authorization.ts","../src/core/lib/flowEngine/executor.ts","../src/core/services/ucanService.ts","../src/core/lib/flowEngine/migration.ts","../src/core/lib/flowEngine/migrations/v0_3_to_v1_0_0.ts"],"sourcesContent":["import type { ActionDefinition } from './types';\n\nconst actions = new Map<string, ActionDefinition>();\n\n/** Maps legacy action type names to their canonical namespaced names. */\nconst ACTION_TYPE_ALIASES: Record<string, string> = {\n bid: 'qi/bid.submit',\n claim: 'qi/claim.submit',\n evaluateBid: 'qi/bid.evaluate',\n evaluateClaim: 'qi/claim.evaluate',\n 'email.send': 'qi/email.send',\n 'http.request': 'qi/http.request',\n 'form.submit': 'qi/form.submit',\n 'human.form.submit': 'qi/human.form.submit',\n 'human.checkbox.set': 'qi/human.checkbox.set',\n 'notification.push': 'qi/notification.push',\n 'proposal.create': 'qi/proposal.create',\n 'proposal.vote': 'qi/proposal.vote',\n 'protocol.select': 'qi/protocol.select',\n 'domain.sign': 'qi/domain.sign',\n 'domain.create': 'qi/domain.create',\n 'credential.store': 'qi/credential.store',\n payment: 'qi/payment.execute',\n 'matrix.dm': 'qi/matrix.dm',\n};\n\nconst aliases = new Map<string, string>(Object.entries(ACTION_TYPE_ALIASES));\n\n/** Resolves a legacy action type name to its canonical namespaced name. */\nexport function resolveActionType(type: string): string {\n return aliases.get(type) ?? type;\n}\n\nexport function registerAction<TInputs extends Record<string, any> = Record<string, any>>(definition: ActionDefinition<TInputs>): void {\n actions.set(definition.type, definition as ActionDefinition);\n}\n\nexport function getAction(type: string): ActionDefinition | undefined {\n return actions.get(resolveActionType(type));\n}\n\nexport function getAllActions(): ActionDefinition[] {\n return Array.from(actions.values());\n}\n\nexport function hasAction(type: string): boolean {\n return actions.has(resolveActionType(type));\n}\n\n/** Look up an action by its UCAN `can` ability string, e.g., \"bid/submit\". */\nexport function getActionByCan(can: string): ActionDefinition | undefined {\n for (const action of actions.values()) {\n if (action.can === can) return action;\n }\n return undefined;\n}\n","/**\n * Bidirectional mapping between UCAN `can` vocabulary and registry `type` strings.\n * Derived mechanically: strip \"qi/\", replace \".\" with \"/\".\n */\n\nconst CAN_TO_TYPE: Record<string, string> = {\n 'bid/submit': 'qi/bid.submit',\n 'bid/evaluate': 'qi/bid.evaluate',\n 'claim/submit': 'qi/claim.submit',\n 'claim/evaluate': 'qi/claim.evaluate',\n 'email/send': 'qi/email.send',\n 'notification/push': 'qi/notification.push',\n 'matrix/dm': 'qi/matrix.dm',\n 'proposal/create': 'qi/proposal.create',\n 'proposal/vote': 'qi/proposal.vote',\n 'domain/create': 'qi/domain.create',\n 'domain/sign': 'qi/domain.sign',\n 'credential/store': 'qi/credential.store',\n 'payment/execute': 'qi/payment.execute',\n 'http/request': 'qi/http.request',\n 'protocol/select': 'qi/protocol.select',\n 'human/checkbox': 'qi/human.checkbox.set',\n 'human/form': 'qi/human.form.submit',\n 'oracle/query': 'oracle',\n};\n\nconst TYPE_TO_CAN: Record<string, string> = Object.fromEntries(Object.entries(CAN_TO_TYPE).map(([can, type]) => [type, can]));\n\n/** Resolve a `can` ability string to the registry `type` string. */\nexport function canToType(can: string): string | undefined {\n return CAN_TO_TYPE[can];\n}\n\n/** Resolve a registry `type` string to the `can` ability string. */\nexport function typeToCan(type: string): string | undefined {\n return TYPE_TO_CAN[type];\n}\n\n/** Get all registered can↔type mappings. */\nexport function getAllCanMappings(): ReadonlyArray<{ can: string; type: string }> {\n return Object.entries(CAN_TO_TYPE).map(([can, type]) => ({ can, type }));\n}\n","import type { ActionServices } from './types';\n\n/**\n * Builds an ActionServices map from BlocknoteHandlers.\n * Used by block components to bridge existing DI into registry calls.\n *\n * The handlers parameter is typed as `any` to avoid a circular dependency\n * between core and mantine layers — BlocknoteHandlers is defined in mantine/context.\n */\nexport function buildServicesFromHandlers(handlers: any): ActionServices {\n return {\n http: {\n request: async (params) => {\n const fetchOptions: RequestInit = {\n method: params.method,\n headers: { 'Content-Type': 'application/json', ...params.headers },\n };\n if (params.method !== 'GET' && params.body) {\n fetchOptions.body = typeof params.body === 'string' ? params.body : JSON.stringify(params.body);\n }\n const res = await fetch(params.url, fetchOptions);\n const data = await res.json().catch(() => ({}));\n const responseHeaders: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n return {\n status: res.status,\n headers: responseHeaders,\n data,\n };\n },\n },\n email: handlers?.sendEmail\n ? {\n send: async (params) => {\n const result = await handlers.sendEmail(params);\n return {\n messageId: result.id || '',\n sentAt: new Date().toISOString(),\n };\n },\n }\n : undefined,\n notify: handlers?.sendNotification\n ? {\n send: async (params) => {\n const result = await handlers.sendNotification(params);\n return {\n messageId: result.messageId,\n sentAt: result.timestamp || new Date().toISOString(),\n };\n },\n }\n : undefined,\n bid:\n handlers?.submitBid && handlers?.approveBid && handlers?.rejectBid && handlers?.approveServiceAgentApplication && handlers?.approveEvaluatorApplication\n ? {\n submitBid: async (params) => handlers.submitBid(params),\n approveBid: async (params) => handlers.approveBid(params),\n rejectBid: async (params) => handlers.rejectBid(params),\n approveServiceAgentApplication: async (params) => handlers.approveServiceAgentApplication(params),\n approveEvaluatorApplication: async (params) => handlers.approveEvaluatorApplication(params),\n }\n : undefined,\n claim:\n handlers?.requestPin && handlers?.submitClaim && handlers?.evaluateClaim && handlers?.getCurrentUser\n ? {\n requestPin: async (config) => handlers.requestPin(config),\n submitClaim: async (params) => handlers.submitClaim(params),\n evaluateClaim: async (granteeAddress, did, payload) => handlers.evaluateClaim(granteeAddress, did, payload),\n getCurrentUser: () => handlers.getCurrentUser(),\n createUdid: handlers?.createUdid ? async (params) => handlers.createUdid(params) : undefined,\n }\n : undefined,\n matrix: handlers?.storeMatrixCredential\n ? {\n storeCredential: async (params) => handlers.storeMatrixCredential(params),\n }\n : undefined,\n };\n}\n","import type { MatrixClient } from 'matrix-js-sdk';\n\n/**\n * Extract the homeserver domain from a Matrix user ID.\n * e.g. \"@user:matrix.ixo.world\" → \"matrix.ixo.world\"\n */\nexport function getHomeserver(matrixClient: MatrixClient): string {\n const userId = matrixClient.getUserId();\n if (!userId) throw new Error('Matrix client has no user ID');\n const idx = userId.indexOf(':');\n if (idx === -1) throw new Error(`Invalid Matrix user ID: ${userId}`);\n return userId.substring(idx + 1);\n}\n\n/**\n * Convert a DID to a Matrix user ID.\n * e.g. \"did:ixo:abc\" → \"@did-ixo-abc:matrix.ixo.world\"\n *\n * This mirrors the reverse mapping in AssignmentTab:\n * matrixUserId.split(':')[0].replace('@', '').replace(/-/g, ':')\n */\nexport function didToMatrixUserId(did: string, homeserver: string): string {\n const localpart = did.replace(/:/g, '-');\n return `@${localpart}:${homeserver}`;\n}\n\n/**\n * Find an existing DM room with the target user, or create one.\n * Uses the `m.direct` account data to track DM room associations.\n */\nexport async function findOrCreateDMRoom(matrixClient: MatrixClient, targetUserId: string): Promise<string> {\n // Check existing DM rooms via m.direct account data\n try {\n const directEvent = (matrixClient as any).getAccountData('m.direct');\n const directContent: Record<string, string[]> = directEvent?.getContent() || {};\n const existingRooms = directContent[targetUserId];\n\n if (existingRooms && existingRooms.length > 0) {\n // Return the first existing DM room\n return existingRooms[0];\n }\n } catch {\n // No m.direct data yet, proceed to create\n }\n\n // Create a new DM room\n const response = await matrixClient.createRoom({\n is_direct: true,\n invite: [targetUserId],\n preset: 'trusted_private_chat' as any,\n initial_state: [],\n });\n\n const roomId = response.room_id;\n\n // Update m.direct account data to include the new room\n try {\n const directEvent = (matrixClient as any).getAccountData('m.direct');\n const directContent: Record<string, string[]> = directEvent?.getContent() || {};\n const updatedContent = {\n ...directContent,\n [targetUserId]: [...(directContent[targetUserId] || []), roomId],\n };\n await (matrixClient as any).setAccountData('m.direct', updatedContent);\n } catch (error) {\n console.warn('[MatrixDM] Failed to update m.direct account data:', error);\n }\n\n return roomId;\n}\n\n/**\n * Send a text message to a Matrix room.\n */\nexport async function sendMatrixMessage(matrixClient: MatrixClient, roomId: string, message: string): Promise<void> {\n await matrixClient.sendEvent(roomId, 'm.room.message' as any, {\n msgtype: 'm.text',\n body: message,\n });\n}\n\n/**\n * Send a direct message to a user identified by DID.\n * Finds or creates a DM room and sends the message.\n */\nexport async function sendDirectMessage(matrixClient: MatrixClient, targetDid: string, message: string): Promise<{ roomId: string }> {\n const homeserver = getHomeserver(matrixClient);\n const targetUserId = didToMatrixUserId(targetDid, homeserver);\n const roomId = await findOrCreateDMRoom(matrixClient, targetUserId);\n await sendMatrixMessage(matrixClient, roomId, message);\n return { roomId };\n}\n","import type { DiffResolver, ActionNarrativeProps } from './diffTypes';\n\nexport interface DiffResolverRegistration {\n resolver: DiffResolver;\n NarrativeComponent?: React.ComponentType<ActionNarrativeProps>;\n}\n\nconst diffResolvers = new Map<string, DiffResolverRegistration>();\n\nexport function registerDiffResolver(actionType: string, reg: DiffResolverRegistration): void {\n diffResolvers.set(actionType, reg);\n}\n\nexport function getDiffResolver(actionType: string): DiffResolverRegistration | undefined {\n return diffResolvers.get(actionType);\n}\n\nexport function hasDiffResolver(actionType: string): boolean {\n return diffResolvers.has(actionType);\n}\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/http.request',\n can: 'http/request',\n sideEffect: false,\n defaultRequiresConfirmation: false,\n\n run: async (inputs, ctx) => {\n const { url, method = 'GET', headers = {}, body } = inputs;\n\n const requestFn = ctx.services.http?.request;\n if (requestFn) {\n const result = await requestFn({ url, method, headers, body });\n return {\n output: {\n status: result.status,\n data: result.data,\n response: JSON.stringify(result.data, null, 2),\n },\n };\n }\n\n // Fallback to native fetch\n const fetchOptions: RequestInit = {\n method,\n headers: { 'Content-Type': 'application/json', ...headers },\n };\n\n if (method !== 'GET' && body) {\n fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body);\n }\n\n const response = await fetch(url, fetchOptions);\n const data = await response.json().catch(() => ({}));\n\n return {\n output: {\n status: response.status,\n data,\n response: JSON.stringify(data, null, 2),\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/email.send',\n can: 'email/send',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'email/send',\n\n outputSchema: [\n { path: 'messageId', displayName: 'Message ID', type: 'string', description: 'The unique ID of the sent email' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'Timestamp when the email was sent' },\n ],\n\n run: async (inputs, ctx) => {\n if (!ctx.services.email) {\n throw new Error('Email service not configured');\n }\n\n const { to, subject, template, templateName, templateVersion, variables, cc, bcc, replyTo } = inputs;\n const resolvedTemplate = template || templateName;\n\n if (!resolvedTemplate) throw new Error('No template selected');\n if (!to) throw new Error('Recipient (to) is required');\n\n // variables may be a JSON string from the config editor — parse if needed\n let resolvedVariables = variables;\n if (typeof resolvedVariables === 'string') {\n try {\n resolvedVariables = JSON.parse(resolvedVariables);\n } catch {\n resolvedVariables = {};\n }\n }\n\n const result = await ctx.services.email.send({\n to,\n subject,\n template: resolvedTemplate,\n templateVersion,\n variables: resolvedVariables,\n cc,\n bcc,\n replyTo,\n });\n\n return {\n output: {\n messageId: result.messageId,\n sentAt: result.sentAt || new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/human.checkbox.set',\n can: 'human/checkbox',\n sideEffect: true,\n defaultRequiresConfirmation: false,\n requiredCapability: 'flow/execute',\n\n run: async (inputs) => {\n // Default to true — \"executing\" a checkbox means checking it\n const checked = inputs.checked !== undefined ? !!inputs.checked : true;\n return { output: { checked } };\n },\n});\n","import { registerAction } from '../registry';\n\nfunction normalizeAnswers(rawAnswers: unknown): Record<string, unknown> {\n if (rawAnswers == null) {\n return {};\n }\n\n if (typeof rawAnswers === 'string') {\n try {\n const parsed = JSON.parse(rawAnswers) as unknown;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error();\n }\n return parsed as Record<string, unknown>;\n } catch {\n throw new Error('answers must be a valid JSON object');\n }\n }\n\n if (typeof rawAnswers !== 'object' || Array.isArray(rawAnswers)) {\n throw new Error('answers must be an object');\n }\n\n return rawAnswers as Record<string, unknown>;\n}\n\nfunction registerFormSubmitAction(type: string, can?: string): void {\n registerAction({\n type,\n can,\n sideEffect: true,\n defaultRequiresConfirmation: false,\n requiredCapability: 'flow/execute',\n outputSchema: [\n { path: 'form.answers', displayName: 'Form Answers JSON', type: 'string', description: 'JSON stringified form answers, matching form block runtime output.' },\n { path: 'answers', displayName: 'Form Answers', type: 'object', description: 'Parsed form answers object for convenience.' },\n ],\n run: async (inputs) => {\n const answers = normalizeAnswers(inputs.answers ?? inputs.form?.answers);\n const answersJson = JSON.stringify(answers);\n\n return {\n output: {\n form: {\n answers: answersJson,\n },\n answers,\n },\n };\n },\n });\n}\n\n// Canonical action type that aligns with the form block naming.\nregisterFormSubmitAction('qi/form.submit', 'form/submit');\n// Backward-compatible alias for existing saved flows.\nregisterFormSubmitAction('qi/human.form.submit', 'human/form');\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/notification.push',\n can: 'notification/push',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'notify/send',\n\n run: async (inputs, ctx) => {\n if (!ctx.services.notify) {\n throw new Error('Notification service not configured');\n }\n\n const { channel, to, cc, bcc, subject, body, bodyType, from, replyTo } = inputs;\n\n if (!to || (Array.isArray(to) && to.length === 0)) {\n throw new Error('At least one recipient is required');\n }\n\n const result = await ctx.services.notify.send({\n channel,\n to: Array.isArray(to) ? to : [to],\n cc,\n bcc,\n subject,\n body,\n bodyType,\n from,\n replyTo,\n });\n\n return {\n output: {\n messageId: result.messageId,\n sentAt: result.sentAt || new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction } from '../../registry';\nimport type { BidRunInputs } from './types';\n\nfunction normalizeBidRole(role: string): 'SA' | 'EA' {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n if (normalized === 'service_agent' || normalized === 'sa') return 'SA';\n if (normalized === 'evaluation_agent' || normalized === 'ea') return 'EA';\n throw new Error('Invalid bid role. Expected service_agent or evaluation_agent');\n}\n\nregisterAction<BidRunInputs>({\n type: 'qi/bid.submit',\n can: 'bid/submit',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: [\n { path: 'bidId', displayName: 'Bid ID', type: 'string', description: 'The submitted bid identifier' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'role', displayName: 'Role', type: 'string', description: 'Submitted role (service_agent or evaluation_agent)' },\n { path: 'submitterDid', displayName: 'Submitter DID', type: 'string', description: 'Actor DID that submitted the bid' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier if provided' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.bid;\n if (!service) {\n throw new Error('Bid service not configured');\n }\n\n const collectionId = String(inputs.collectionId || '').trim();\n const roleInput = String(inputs.role || '').trim();\n let surveyAnswers = inputs.surveyAnswers;\n const deedDid = String(inputs.deedDid || '').trim();\n\n if (!collectionId) throw new Error('collectionId is required');\n if (!roleInput) throw new Error('role is required');\n if (typeof surveyAnswers === 'string') {\n try {\n surveyAnswers = JSON.parse(surveyAnswers);\n } catch {\n throw new Error('surveyAnswers must be a valid JSON object');\n }\n }\n\n if (!surveyAnswers || typeof surveyAnswers !== 'object' || Array.isArray(surveyAnswers)) {\n throw new Error('surveyAnswers must be an object');\n }\n\n const chainRole = normalizeBidRole(roleInput);\n const submission = await service.submitBid({\n collectionId,\n role: chainRole,\n surveyAnswers,\n });\n\n const bidId = String((submission as any)?.claimId || (submission as any)?.bidId || (submission as any)?.id || '');\n if (!bidId) {\n throw new Error('submitBid returned no bid identifier');\n }\n\n return {\n output: {\n bidId,\n collectionId,\n role: roleInput,\n submitterDid: ctx.actorDid || '',\n deedDid,\n },\n };\n },\n});\n","import { registerAction } from '../../registry';\nimport type { EvaluateBidRunInputs } from './types';\n\ntype Decision = 'approve' | 'reject';\n\nfunction normalizeDecision(value: string): Decision {\n const normalized = String(value || '')\n .trim()\n .toLowerCase();\n if (normalized === 'approve' || normalized === 'reject') {\n return normalized;\n }\n throw new Error('decision must be either approve or reject');\n}\n\nfunction isServiceAgentRole(role: string): boolean {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n return normalized === 'service_agent' || normalized === 'sa';\n}\n\nfunction isEvaluationAgentRole(role: string): boolean {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n return normalized === 'evaluation_agent' || normalized === 'ea';\n}\n\nregisterAction<EvaluateBidRunInputs>({\n type: 'qi/bid.evaluate',\n can: 'bid/evaluate',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: [\n { path: 'bidId', displayName: 'Bid ID', type: 'string', description: 'Evaluated bid identifier' },\n { path: 'decision', displayName: 'Decision', type: 'string', description: 'approve or reject' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'approved or rejected' },\n { path: 'evaluatedByDid', displayName: 'Evaluated By DID', type: 'string', description: 'Actor DID that evaluated the bid' },\n { path: 'evaluatedAt', displayName: 'Evaluated At', type: 'string', description: 'ISO timestamp of evaluation' },\n { path: 'reason', displayName: 'Reason', type: 'string', description: 'Rejection reason when decision is reject' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'role', displayName: 'Role', type: 'string', description: 'Applicant role' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier' },\n { path: 'applicantDid', displayName: 'Applicant DID', type: 'string', description: 'Applicant DID' },\n { path: 'applicantAddress', displayName: 'Applicant Address', type: 'string', description: 'Applicant wallet address' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.bid;\n if (!service) {\n throw new Error('Bid service not configured');\n }\n\n const decision = normalizeDecision(inputs.decision);\n const bidId = String(inputs.bidId || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || '').trim();\n const role = String(inputs.role || '').trim();\n const applicantDid = String(inputs.applicantDid || '').trim();\n const applicantAddress = String(inputs.applicantAddress || '').trim();\n\n if (!bidId) throw new Error('bidId is required');\n if (!collectionId) throw new Error('collectionId is required');\n if (!deedDid) throw new Error('deedDid is required');\n if (!role) throw new Error('role is required');\n if (!applicantDid) throw new Error('applicantDid is required');\n if (!applicantAddress) throw new Error('applicantAddress is required');\n\n if (decision === 'approve') {\n const adminAddress = String(inputs.adminAddress || '').trim();\n if (!adminAddress) {\n throw new Error('adminAddress is required when decision is approve');\n }\n\n if (isServiceAgentRole(role)) {\n await service.approveServiceAgentApplication({\n adminAddress,\n collectionId,\n agentQuota: 30,\n deedDid,\n currentUserAddress: applicantAddress,\n });\n } else if (isEvaluationAgentRole(role)) {\n let maxAmounts = inputs.maxAmounts;\n if (typeof maxAmounts === 'string') {\n try {\n maxAmounts = JSON.parse(maxAmounts);\n } catch {\n throw new Error('maxAmounts must be valid JSON when provided');\n }\n }\n\n await service.approveEvaluatorApplication({\n adminAddress,\n collectionId,\n deedDid,\n evaluatorAddress: applicantAddress,\n agentQuota: 10,\n maxAmounts: Array.isArray(maxAmounts) ? maxAmounts : undefined,\n });\n } else {\n throw new Error('Invalid role for evaluation. Expected service_agent or evaluation_agent');\n }\n\n await service.approveBid({\n bidId,\n collectionId,\n did: applicantDid,\n });\n } else {\n const reason = String(inputs.reason || '').trim();\n if (!reason) {\n throw new Error('reason is required when decision is reject');\n }\n await service.rejectBid({\n bidId,\n collectionId,\n did: deedDid,\n reason,\n });\n }\n\n return {\n output: {\n bidId,\n decision,\n status: decision === 'approve' ? 'approved' : 'rejected',\n evaluatedByDid: ctx.actorDid || '',\n evaluatedAt: new Date().toISOString(),\n reason: decision === 'reject' ? String(inputs.reason || '') : '',\n collectionId,\n role,\n deedDid,\n applicantDid,\n applicantAddress,\n },\n };\n },\n});\n","import { registerAction } from '../../registry';\nimport type { ClaimRunInputs } from './types';\n\nregisterAction<ClaimRunInputs>({\n type: 'qi/claim.submit',\n can: 'claim/submit',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: [\n { path: 'claimId', displayName: 'Claim ID', type: 'string', description: 'The submitted claim identifier' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'Submission transaction hash' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier' },\n { path: 'submittedByDid', displayName: 'Submitted By DID', type: 'string', description: 'Actor DID that submitted the claim' },\n { path: 'submittedAt', displayName: 'Submitted At', type: 'string', description: 'ISO timestamp of submission' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.claim;\n if (!service) {\n throw new Error('Claim service not configured');\n }\n\n const deedDid = String(inputs.deedDid || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const adminAddress = String(inputs.adminAddress || '').trim();\n\n if (!deedDid) throw new Error('deedDid is required');\n if (!collectionId) throw new Error('collectionId is required');\n if (!adminAddress) throw new Error('adminAddress is required');\n\n let surveyAnswers = inputs.surveyAnswers;\n if (typeof surveyAnswers === 'string') {\n try {\n surveyAnswers = JSON.parse(surveyAnswers);\n } catch {\n throw new Error('surveyAnswers must be valid JSON');\n }\n }\n\n if (!surveyAnswers || typeof surveyAnswers !== 'object' || Array.isArray(surveyAnswers)) {\n throw new Error('surveyAnswers must be an object');\n }\n\n let pin = String(inputs.pin || '').trim();\n if (!pin) {\n pin = await service.requestPin({\n title: 'Verify Identity',\n description: 'Enter your PIN to submit the claim',\n submitText: 'Verify',\n });\n }\n if (!pin) {\n throw new Error('PIN is required to submit claim');\n }\n\n const result = await service.submitClaim({\n surveyData: surveyAnswers,\n deedDid,\n collectionId,\n adminAddress,\n pin,\n });\n\n const claimId = String((result as any)?.claimId || (result as any)?.id || '');\n if (!claimId) {\n throw new Error('submitClaim returned no claim identifier');\n }\n\n return {\n output: {\n claimId,\n transactionHash: String((result as any)?.transactionHash || ''),\n collectionId,\n deedDid,\n submittedByDid: ctx.actorDid || '',\n submittedAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction } from '../../registry';\nimport type { EvaluateClaimRunInputs } from './types';\n\ntype Decision = 'approve' | 'reject';\n\nfunction normalizeDecision(value: unknown): Decision {\n const normalized = String(value || '')\n .trim()\n .toLowerCase();\n if (normalized === 'approve' || normalized === 'reject') {\n return normalized;\n }\n throw new Error('decision must be either approve or reject');\n}\n\nfunction toStatus(decision: Decision): number {\n return decision === 'approve' ? 1 : 2;\n}\n\nfunction isEvaluatorRole(role: unknown): boolean {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n return normalized === 'ea' || normalized === 'evaluation_agent';\n}\n\nregisterAction<EvaluateClaimRunInputs>({\n type: 'qi/claim.evaluate',\n can: 'claim/evaluate',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: [\n { path: 'claimId', displayName: 'Claim ID', type: 'string', description: 'Evaluated claim identifier' },\n { path: 'decision', displayName: 'Decision', type: 'string', description: 'approve or reject' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'approved or rejected' },\n { path: 'verificationProof', displayName: 'Verification Proof', type: 'string', description: 'UDID URL proof if generated' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier' },\n { path: 'evaluatedByDid', displayName: 'Evaluated By DID', type: 'string', description: 'Actor DID that evaluated the claim' },\n { path: 'evaluatedAt', displayName: 'Evaluated At', type: 'string', description: 'ISO timestamp of evaluation' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.claim;\n if (!service) {\n throw new Error('Claim service not configured');\n }\n\n const decision = normalizeDecision(inputs.decision);\n const claimId = String(inputs.claimId || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || '').trim();\n const adminAddress = String(inputs.adminAddress || '').trim();\n\n if (!claimId) throw new Error('claimId is required');\n if (!collectionId) throw new Error('collectionId is required');\n if (!deedDid) throw new Error('deedDid is required');\n if (!adminAddress) throw new Error('adminAddress is required');\n\n // Action-level authorization guard: evaluator role is required.\n const handlers = ctx.handlers as any;\n const actorAddress = String(ctx.actorDid || service.getCurrentUser?.()?.address || '').trim();\n if (!actorAddress) {\n throw new Error('Unable to resolve actor address for evaluator authorization');\n }\n\n if (typeof handlers?.getUserRoles !== 'function') {\n throw new Error('Evaluator authorization check unavailable (getUserRoles handler missing)');\n }\n\n const roles = await handlers.getUserRoles({\n userAddress: actorAddress,\n adminAddress,\n deedDid,\n collectionIds: [collectionId],\n });\n\n const roleForCollection = Array.isArray(roles) ? roles.find((r: any) => r?.collectionId === collectionId)?.role : undefined;\n if (!isEvaluatorRole(roleForCollection)) {\n throw new Error('Not authorized: evaluator role required to evaluate claims for this collection');\n }\n\n let amount = inputs.amount;\n if (typeof amount === 'string' && amount.trim()) {\n try {\n amount = JSON.parse(amount);\n } catch {\n throw new Error('amount must be valid JSON when provided as string');\n }\n }\n\n const normalizeCoin = (coin: any) => {\n if (!coin || typeof coin !== 'object' || Array.isArray(coin)) return null;\n const denom = String(coin.denom || '').trim();\n const tokenAmount = String(coin.amount || '').trim();\n if (!denom || !tokenAmount) return null;\n return { denom, amount: tokenAmount };\n };\n\n let normalizedAmounts: Array<{ denom: string; amount: string }> | undefined;\n if (Array.isArray(amount)) {\n normalizedAmounts = amount.map(normalizeCoin).filter((coin): coin is { denom: string; amount: string } => !!coin);\n if (normalizedAmounts.length !== amount.length) {\n throw new Error('amount must contain valid coin objects with denom and amount');\n }\n } else if (amount != null) {\n const coin = normalizeCoin(amount);\n if (!coin) {\n throw new Error('amount must be a coin object or an array of coin objects');\n }\n normalizedAmounts = [coin];\n }\n\n let verificationProof = String(inputs.verificationProof || '').trim();\n const shouldCreateUdid = Boolean(inputs.createUdid);\n\n if (!verificationProof && shouldCreateUdid && service.createUdid) {\n const pin = await service.requestPin({\n title: 'Sign Evaluation Result',\n description: 'Enter your PIN to sign the evaluation UDID',\n submitText: 'Sign',\n });\n\n if (!pin) {\n throw new Error('PIN is required to sign evaluation proof');\n }\n\n const udid = await service.createUdid({\n claimCid: claimId,\n deedDid,\n collectionId,\n capabilityCid: String(inputs.capabilityCid || deedDid),\n rubricAuthority: String(inputs.rubricAuthority || deedDid),\n rubricId: String(inputs.rubricId || deedDid),\n outcome: toStatus(decision),\n tag: decision === 'approve' ? 'approved' : 'rejected',\n issuerType: 'user',\n pin,\n traceCid: inputs.traceCid,\n items: inputs.items,\n patch: inputs.patch as Record<string, any> | undefined,\n });\n\n verificationProof = String((udid as any)?.url || (udid as any)?.cid || '');\n }\n\n const currentUser = service.getCurrentUser();\n const granteeAddress = String((inputs.granteeAddress as string) || currentUser?.address || '').trim();\n if (!granteeAddress) {\n throw new Error('granteeAddress could not be resolved');\n }\n\n await service.evaluateClaim(granteeAddress, deedDid, {\n claimId,\n collectionId,\n adminAddress,\n status: toStatus(decision),\n verificationProof,\n amount: normalizedAmounts && normalizedAmounts.length > 0 ? (normalizedAmounts.length === 1 ? normalizedAmounts[0] : normalizedAmounts) : undefined,\n });\n\n return {\n output: {\n claimId,\n decision,\n status: decision === 'approve' ? 'approved' : 'rejected',\n verificationProof,\n collectionId,\n deedDid,\n evaluatedByDid: ctx.actorDid || granteeAddress,\n evaluatedAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/proposal.create',\n can: 'proposal/create',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n outputSchema: [\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The on-chain proposal identifier' },\n { path: 'status', displayName: 'Proposal Status', type: 'string', description: 'Current proposal status (open, passed, rejected, executed, etc.)' },\n { path: 'proposalContractAddress', displayName: 'Proposal Contract Address', type: 'string', description: 'The proposal module contract address' },\n { path: 'coreAddress', displayName: 'Core Address', type: 'string', description: 'The DAO core contract address' },\n { path: 'createdAt', displayName: 'Created At', type: 'string', description: 'ISO timestamp of proposal creation' },\n ],\n\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n\n const coreAddress = String(inputs.coreAddress || '').trim();\n const title = String(inputs.title || '').trim();\n const description = String(inputs.description || '').trim();\n\n if (!coreAddress) throw new Error('coreAddress is required');\n if (!title) throw new Error('title is required');\n if (!description) throw new Error('description is required');\n\n let actions: any[] = [];\n if (inputs.actions) {\n if (typeof inputs.actions === 'string') {\n try {\n actions = JSON.parse(inputs.actions);\n } catch {\n throw new Error('actions must be valid JSON array');\n }\n } else if (Array.isArray(inputs.actions)) {\n actions = inputs.actions;\n }\n }\n\n // Get pre-proposal and group contract addresses\n const { preProposalContractAddress } = await handlers.getPreProposalContractAddress({\n coreAddress,\n });\n\n const { groupContractAddress } = await handlers.getGroupContractAddress({\n coreAddress,\n });\n\n const { proposalContractAddress } = await handlers.getProposalContractAddress({\n coreAddress,\n });\n\n const params = {\n preProposalContractAddress,\n title,\n description,\n actions: actions.length > 0 ? actions : undefined,\n coreAddress,\n groupContractAddress,\n };\n\n const proposalId = await handlers.createProposal(params);\n\n return {\n output: {\n proposalId: String(proposalId),\n status: 'open',\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n createdAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/proposal.vote',\n can: 'proposal/vote',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n outputSchema: [\n { path: 'vote', displayName: 'Vote', type: 'string', description: 'The vote cast (yes, no, no_with_veto, abstain)' },\n { path: 'rationale', displayName: 'Rationale', type: 'string', description: 'Optional rationale provided with the vote' },\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The proposal that was voted on' },\n { path: 'votedAt', displayName: 'Voted At', type: 'string', description: 'ISO timestamp of when the vote was cast' },\n ],\n\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n\n const proposalId = Number(inputs.proposalId);\n const vote = String(inputs.vote || '').trim();\n const rationale = String(inputs.rationale || '').trim();\n const proposalContractAddress = String(inputs.proposalContractAddress || '').trim();\n\n if (!proposalId || isNaN(proposalId)) throw new Error('proposalId is required');\n if (!vote) throw new Error('vote is required');\n if (!proposalContractAddress) throw new Error('proposalContractAddress is required');\n\n const validVotes = ['yes', 'no', 'no_with_veto', 'abstain'];\n if (!validVotes.includes(vote)) {\n throw new Error(`vote must be one of: ${validVotes.join(', ')}`);\n }\n\n await handlers.vote({\n proposalId,\n vote,\n rationale: rationale || undefined,\n proposalContractAddress,\n });\n\n return {\n output: {\n vote,\n rationale: rationale || '',\n proposalId: String(proposalId),\n votedAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/protocol.select',\n can: 'protocol/select',\n sideEffect: false,\n defaultRequiresConfirmation: false,\n\n outputSchema: [\n { path: 'selectedProtocolDid', displayName: 'Selected Protocol DID', type: 'string', description: 'DID of the selected protocol' },\n { path: 'selectedProtocolName', displayName: 'Selected Protocol Name', type: 'string', description: 'Display name of the selected protocol' },\n { path: 'selectedProtocolType', displayName: 'Selected Protocol Type', type: 'string', description: 'Type of the selected protocol' },\n ],\n\n run: async (inputs, _ctx) => {\n const selectedProtocolDid = String(inputs.selectedProtocolDid || '').trim();\n const selectedProtocolName = String(inputs.selectedProtocolName || '').trim();\n const selectedProtocolType = String(inputs.selectedProtocolType || '').trim();\n\n if (!selectedProtocolDid) throw new Error('selectedProtocolDid is required');\n\n return {\n output: {\n selectedProtocolDid,\n selectedProtocolName,\n selectedProtocolType,\n },\n };\n },\n});\n","/**\n * Builds an unsigned W3C Verifiable Credential envelope for a Domain Card.\n * The credential follows the ixo:DomainCard schema.\n */\n\nimport type { DomainCardCredentialSubject } from './transformSurveyToCredentialSubject';\n\n/**\n * JSON-LD context for Domain Card credentials\n */\nexport const DOMAIN_CARD_CONTEXT = [\n 'https://w3id.org/ixo/context/v1',\n {\n schema: 'https://schema.org/',\n ixo: 'https://w3id.org/ixo/vocab/v1',\n prov: 'http://www.w3.org/ns/prov#',\n proj: 'http://www.w3.org/ns/project#',\n id: '@id',\n type: '@type',\n '@protected': true,\n },\n] as const;\n\n/**\n * Domain Card credential schema reference\n */\nexport const DOMAIN_CARD_SCHEMA = {\n id: 'https://w3id.org/ixo/protocol/schema/v1#domainCard',\n type: 'JsonSchema',\n} as const;\n\n/**\n * DataIntegrityProof structure for signed credentials\n */\nexport interface DataIntegrityProof {\n type: 'DataIntegrityProof';\n created: string;\n verificationMethod: string;\n cryptosuite: 'eddsa-rdfc-2022';\n proofPurpose: 'assertionMethod';\n proofValue: string;\n}\n\n/**\n * Unsigned Verifiable Credential structure\n */\nexport interface UnsignedVerifiableCredential {\n '@context': typeof DOMAIN_CARD_CONTEXT;\n id: string;\n type: ['VerifiableCredential', 'ixo:DomainCard'];\n issuer: {\n id: string;\n };\n validFrom: string;\n validUntil: string;\n credentialSchema: typeof DOMAIN_CARD_SCHEMA;\n credentialSubject: DomainCardCredentialSubject;\n}\n\n/**\n * Signed Verifiable Credential with proof\n */\nexport interface SignedVerifiableCredential extends UnsignedVerifiableCredential {\n proof: DataIntegrityProof;\n}\n\n/**\n * Base credential subject with required fields.\n * Used for flexible input that may come from different sources (survey, existing credential, etc.)\n */\nexport interface BaseCredentialSubject {\n id: string;\n type: string[];\n name: string;\n description: string;\n [key: string]: unknown; // Allow additional properties\n}\n\n/**\n * Parameters for building an unsigned verifiable credential\n */\nexport interface BuildCredentialParams {\n /** DID of the entity this domain card describes */\n entityDid: string;\n /** DID of the issuer signing this credential */\n issuerDid: string;\n /** The credential subject containing domain card data (flexible input) */\n credentialSubject: BaseCredentialSubject | DomainCardCredentialSubject;\n /** ISO 8601 date string for when credential becomes valid */\n validFrom: string;\n /** ISO 8601 date string for when credential expires */\n validUntil: string;\n}\n\n/**\n * Converts a date input to ISO 8601 string format.\n * Handles various input formats from survey fields.\n */\nfunction toISOString(dateInput: string | Date | undefined, fallback: Date = new Date()): string {\n if (!dateInput) {\n return fallback.toISOString();\n }\n\n if (dateInput instanceof Date) {\n return dateInput.toISOString();\n }\n\n // Handle date-only strings (YYYY-MM-DD) from date inputs\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(dateInput)) {\n return new Date(dateInput + 'T00:00:00.000Z').toISOString();\n }\n\n // Handle datetime-local strings (YYYY-MM-DDTHH:MM)\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}$/.test(dateInput)) {\n return new Date(dateInput + ':00.000Z').toISOString();\n }\n\n // Try parsing as-is\n const parsed = new Date(dateInput);\n if (!isNaN(parsed.getTime())) {\n return parsed.toISOString();\n }\n\n return fallback.toISOString();\n}\n\n/**\n * Calculates a default expiration date (5 years from validFrom).\n */\nfunction getDefaultValidUntil(validFrom: string): string {\n const fromDate = new Date(validFrom);\n const untilDate = new Date(fromDate);\n untilDate.setFullYear(untilDate.getFullYear() + 5);\n return untilDate.toISOString();\n}\n\n/**\n * Builds an unsigned verifiable credential for a Domain Card.\n *\n * @param params - Parameters for building the credential\n * @returns An unsigned verifiable credential ready for signing\n *\n * @example\n * ```typescript\n * const credential = buildVerifiableCredential({\n * entityDid: 'did:ixo:entity:abc123',\n * issuerDid: 'did:ixo:ixo1xyz...',\n * credentialSubject: transformedSubject,\n * validFrom: '2025-01-01',\n * validUntil: '2030-01-01',\n * });\n * ```\n */\nexport function buildVerifiableCredential(params: BuildCredentialParams): UnsignedVerifiableCredential {\n const { entityDid, issuerDid, credentialSubject, validFrom, validUntil } = params;\n\n const validFromISO = toISOString(validFrom);\n const validUntilISO = validUntil ? toISOString(validUntil) : getDefaultValidUntil(validFromISO);\n\n return {\n '@context': DOMAIN_CARD_CONTEXT,\n id: `${entityDid}#dmn`,\n type: ['VerifiableCredential', 'ixo:DomainCard'],\n issuer: {\n id: issuerDid,\n },\n validFrom: validFromISO,\n validUntil: validUntilISO,\n credentialSchema: DOMAIN_CARD_SCHEMA,\n credentialSubject: {\n ...credentialSubject,\n // Ensure the subject ID matches the entity DID\n id: entityDid,\n },\n };\n}\n\n/**\n * LinkedResource structure for storing the credential on-chain\n */\nexport interface DomainCardLinkedResource {\n id: string;\n type: 'domainCard';\n proof: string;\n right: string;\n encrypted: string;\n mediaType: 'application/json';\n description: string;\n serviceEndpoint: string;\n}\n\n/**\n * Builds a LinkedResource object for a Domain Card credential.\n *\n * @param params - Parameters for building the linked resource\n * @returns A LinkedResource object ready to be added to an entity\n *\n * @example\n * ```typescript\n * const linkedResource = buildDomainCardLinkedResource({\n * entityDid: 'did:ixo:entity:abc123',\n * cid: 'bafkreid2t3hp7qi6ynyvaz4o3bphyjtqcz2qwlhm4odvuvesnh6dtv3hvu',\n * serviceEndpoint: 'https://mx.ixo.earth/_matrix/media/v3/download/...',\n * });\n * ```\n */\nexport function buildDomainCardLinkedResource(params: { entityDid: string; cid: string; serviceEndpoint: string; description?: string }): DomainCardLinkedResource {\n return {\n id: `${params.entityDid}#dmn`,\n type: 'domainCard',\n proof: params.cid,\n right: '',\n encrypted: 'false',\n mediaType: 'application/json',\n description: params.description || 'Domain Card',\n serviceEndpoint: params.serviceEndpoint,\n };\n}\n","import type { LinkedEntityData } from '../../governanceGroup/types';\n\n/**\n * LinkedEntity structure for createDomain call\n */\nexport interface LinkedEntity {\n id: string;\n type: string;\n relationship: string;\n service: string;\n}\n\n/**\n * Parse linked entities from block props\n */\nexport function parseLinkedEntities(entitiesString: string): LinkedEntityData[] {\n if (!entitiesString || entitiesString === '[]') return [];\n try {\n return JSON.parse(entitiesString) as LinkedEntityData[];\n } catch {\n return [];\n }\n}\n\n/**\n * Build LinkedEntity array for governance groups\n * These will be passed to createDomain as linkedEntity parameter\n */\nexport function buildGovernanceGroupLinkedEntities(linkedEntities: LinkedEntityData[]): LinkedEntity[] {\n return linkedEntities\n .filter((entity) => entity.type === 'governanceGroup' && entity.coreAddress)\n .map((entity) => ({\n id: entity.coreAddress,\n type: 'group',\n relationship: 'governs',\n service: '',\n }));\n}\n","import { registerAction } from '../registry';\nimport { buildVerifiableCredential } from '@/mantine/blocks/domainCreator/utils/buildVerifiableCredential';\nimport { buildDomainCardLinkedResource } from '@/mantine/blocks/domainCreator/utils/buildVerifiableCredential';\nimport { parseLinkedEntities, buildGovernanceGroupLinkedEntities } from '@/mantine/blocks/domainCreatorSign/utils/buildLinkedEntityResource';\n\nregisterAction({\n type: 'qi/domain.sign',\n can: 'domain/sign',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n outputSchema: [\n { path: 'entityDid', displayName: 'Entity DID', type: 'string', description: 'The DID of the newly created domain entity' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The on-chain transaction hash for domain creation' },\n ],\n\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n\n if (!handlers.requestPin) throw new Error('requestPin handler not available');\n if (!handlers.signCredential) throw new Error('signCredential handler not implemented');\n if (!handlers.publicFileUpload) throw new Error('publicFileUpload handler not available');\n if (!handlers.createDomain) throw new Error('createDomain handler not implemented');\n\n // Parse domainCardData input\n let domainCardData: any;\n if (typeof inputs.domainCardData === 'string') {\n try {\n domainCardData = JSON.parse(inputs.domainCardData);\n } catch {\n throw new Error('domainCardData must be valid JSON');\n }\n } else if (inputs.domainCardData && typeof inputs.domainCardData === 'object') {\n domainCardData = inputs.domainCardData;\n } else {\n throw new Error('domainCardData is required');\n }\n\n if (!domainCardData?.credentialSubject?.name) {\n throw new Error('domainCardData is missing or invalid (credentialSubject.name required)');\n }\n\n // Determine entity type\n const extractEntityType = (type: string): string => type.replace(/^schema:/i, '').toLowerCase();\n const entityType =\n String(inputs.entityType || '').trim() || (domainCardData.credentialSubject?.type?.[0] ? extractEntityType(domainCardData.credentialSubject.type[0]) : 'dao');\n\n // Get issuer DID\n const issuerDid = handlers.getEntityDid?.() || handlers.getCurrentUser?.()?.address;\n if (!issuerDid) throw new Error('Unable to determine issuer DID');\n\n // Placeholder DID for new entity (will be replaced after creation)\n const entityDidPlaceholder = 'did:ixo:entity:pending';\n\n const validFrom = domainCardData.validFrom || new Date().toISOString();\n const validUntil =\n domainCardData.validUntil ||\n (() => {\n const d = new Date();\n d.setFullYear(d.getFullYear() + 100);\n return d.toISOString();\n })();\n\n const credentialSubject = {\n ...domainCardData.credentialSubject,\n id: entityDidPlaceholder,\n };\n\n const unsignedCredential = buildVerifiableCredential({\n entityDid: entityDidPlaceholder,\n issuerDid,\n credentialSubject,\n validFrom,\n validUntil,\n });\n\n // Step 1: Request PIN and sign credential\n const pin = await handlers.requestPin({\n title: 'Sign Domain Card',\n description: 'Enter your PIN to sign the Domain Card credential',\n submitText: 'Sign',\n });\n\n const { signedCredential } = await handlers.signCredential({\n issuerDid,\n issuerType: 'user',\n credential: unsignedCredential,\n pin,\n });\n\n // Step 2: Upload signed credential\n const credentialBlob = new Blob([JSON.stringify(signedCredential, null, 2)], {\n type: 'application/json',\n });\n const credentialFile = new File([credentialBlob], 'domainCard.json', {\n type: 'application/json',\n });\n\n const uploadResult = await handlers.publicFileUpload(credentialFile);\n\n // Step 3: Build linked resource and linked entities\n const domainCardLinkedResource = buildDomainCardLinkedResource({\n entityDid: entityDidPlaceholder,\n cid: uploadResult.cid,\n serviceEndpoint: uploadResult.url,\n description: `Domain Card for ${domainCardData.credentialSubject?.name || 'Domain'}`,\n });\n\n // Parse optional linkedEntities input\n let linkedEntitiesData: any[] = [];\n if (inputs.linkedEntities) {\n if (typeof inputs.linkedEntities === 'string') {\n try {\n linkedEntitiesData = JSON.parse(inputs.linkedEntities);\n } catch {\n // Ignore invalid JSON\n }\n } else if (Array.isArray(inputs.linkedEntities)) {\n linkedEntitiesData = inputs.linkedEntities;\n }\n }\n\n const governanceGroupLinkedEntities = buildGovernanceGroupLinkedEntities(parseLinkedEntities(JSON.stringify(linkedEntitiesData)));\n\n const endDate = domainCardData.endDate || validUntil;\n\n // Step 4: Create domain entity\n const { entityDid: newEntityDid, transactionHash } = await handlers.createDomain({\n entityType,\n linkedResource: [domainCardLinkedResource],\n linkedEntity: governanceGroupLinkedEntities.length > 0 ? governanceGroupLinkedEntities : undefined,\n startDate: validFrom,\n endDate,\n });\n\n return {\n output: {\n entityDid: newEntityDid,\n transactionHash,\n },\n };\n },\n});\n","/**\n * Transforms survey data from the Domain Creator survey into a W3C Verifiable Credential\n * credentialSubject structure compatible with ixo:DomainCard schema.\n */\n\nexport interface DomainCardCredentialSubject {\n id: string;\n type: string[];\n additionalType?: string[];\n name: string;\n alternateName?: string[];\n description: string;\n url?: string;\n sameAs?: string[];\n logo?: {\n type: string;\n id: string;\n contentUrl: string;\n };\n image?: Array<{\n type: string;\n id: string;\n contentUrl: string;\n }>;\n keywords?: string[];\n knowsAbout?: string[];\n address?: {\n type: string;\n streetAddress?: string;\n addressLocality?: string;\n addressRegion?: string;\n postalCode?: string;\n addressCountry?: string;\n };\n areaServed?: {\n type: string;\n name: string;\n };\n contactPoint?: Array<{\n type: string;\n contactType: string;\n email?: string;\n telephone?: string;\n availableLanguage?: string[];\n }>;\n composition?: {\n type: string;\n hasPart?: Array<{\n type: string;\n id?: string;\n name?: string;\n description?: string;\n url?: string;\n creator?: {\n type: string;\n name: string;\n };\n }>;\n subjectOf?: Array<{\n type: string;\n name: string;\n url?: string;\n author?: {\n type: string;\n name: string;\n };\n }>;\n };\n makesOffer?: Array<{\n type: string;\n name?: string;\n description?: string;\n itemOffered?: {\n type: string;\n name?: string;\n url?: string;\n };\n }>;\n relationships?: {\n memberOf?: Array<{\n type: string;\n name: string;\n }>;\n 'prov:wasAssociatedWith'?: Array<{\n type: string;\n name: string;\n url?: string;\n }>;\n funding?: Array<{\n type: string;\n funder?: {\n type: string;\n name: string;\n };\n amount?: {\n type: string;\n currency: string;\n value: string;\n };\n }>;\n };\n agents?: Array<{\n type: string;\n id?: string;\n name?: string;\n description?: string;\n }>;\n credentials?: Array<{\n type: string;\n id?: string;\n name?: string;\n description?: string;\n }>;\n attributes?: Array<{\n '@type': string;\n '@id': string;\n name: string;\n value: string;\n }>;\n project?: {\n type?: string;\n name?: string;\n description?: string;\n hadObjective?: string[];\n plannedStart?: string;\n plannedEnd?: string;\n wasFundedThrough?: Array<{\n type: string;\n moneyAmount?: string;\n moneyCurrency?: string;\n agent?: {\n type: string;\n id?: string;\n name?: string;\n };\n }>;\n };\n researchProfile?: {\n type: string;\n 'ixo:seedQueries'?: string[];\n citation?: Array<{\n type: string;\n name: string;\n url?: string;\n publisher?: string;\n datePublished?: string;\n }>;\n 'ixo:embedding'?: {\n type: string;\n id: string;\n model: string;\n contentUrl: string;\n };\n dateModified?: string;\n };\n}\n\n/**\n * Helper to extract array items from paneldynamic survey fields\n */\nfunction extractPanelDynamicItems<T>(surveyData: Record<string, any>, panelName: string, itemMapper: (item: Record<string, any>) => T | null): T[] {\n const items = surveyData[panelName];\n if (!Array.isArray(items)) return [];\n return items.map(itemMapper).filter((item): item is T => item !== null);\n}\n\n/**\n * Parse comma-separated string into array of trimmed strings\n */\nfunction parseCommaSeparated(value: string | undefined): string[] {\n if (!value || typeof value !== 'string') return [];\n return value\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\n/**\n * Parse language codes from comma-separated string\n */\nfunction parseLanguageCodes(value: string | undefined): string[] {\n return parseCommaSeparated(value);\n}\n\n/**\n * Build image object from URL\n */\nfunction buildImageObject(url: string | undefined): { type: string; id: string; contentUrl: string } | null {\n if (!url) return null;\n return {\n type: 'schema:ImageObject',\n id: url,\n contentUrl: url,\n };\n}\n\n/**\n * Main transformation function\n */\nexport function transformSurveyToCredentialSubject(surveyData: Record<string, any>, entityDid: string): DomainCardCredentialSubject {\n // Build type array from survey selections\n const types: string[] = [];\n if (surveyData['type_1']) types.push(`ixo:${surveyData['type_1']}`);\n if (surveyData['type_2']) types.push(surveyData['type_2']);\n\n // Build additionalType from daoType\n const additionalType: string[] = [];\n if (surveyData['daoType']) additionalType.push(surveyData['daoType']);\n\n // Extract alternate names from paneldynamic\n const alternateNames = extractPanelDynamicItems(surveyData, 'pannel_schema:alternateName', (item) => item['schema:alternateName'] || null);\n\n // Extract sameAs URLs from paneldynamic\n const sameAsUrls = extractPanelDynamicItems(surveyData, 'schema:sameAs', (item) => item['schema:sameAs.url'] || null);\n\n // Build logo from URL or uploaded file\n const logoUrl = surveyData['ixo:imageLogo_url'] || surveyData['ixo:imageLogo']?.[0]?.content;\n const logo = buildImageObject(logoUrl);\n\n // Build profile image from URL or uploaded file\n const profileImageUrl = surveyData['ixo:imageProfile_url'] || surveyData['ixo:imageProfile']?.[0]?.content;\n const profileImage = buildImageObject(profileImageUrl);\n\n // Parse keywords from comma-separated string\n const keywords = parseCommaSeparated(surveyData['schema:keywords']);\n\n // Extract knowsAbout from paneldynamic\n const knowsAbout = extractPanelDynamicItems(surveyData, 'pannel_ixo:knowsAbout', (item) => item['ixo:knowsAbout'] || null);\n\n // Build address object\n const hasAddressData =\n surveyData['schema:streetAddress'] ||\n surveyData['schema:addressLocality'] ||\n surveyData['schema:addressRegion'] ||\n surveyData['schema:postalCode'] ||\n surveyData['schema:addressCountry'];\n\n const address = hasAddressData\n ? {\n type: 'schema:PostalAddress',\n streetAddress: surveyData['schema:streetAddress'] || undefined,\n addressLocality: surveyData['schema:addressLocality'] || undefined,\n addressRegion: surveyData['schema:addressRegion'] || undefined,\n postalCode: surveyData['schema:postalCode'] || undefined,\n addressCountry: surveyData['schema:addressCountry'] || undefined,\n }\n : undefined;\n\n // Build areaServed\n const areaServed = surveyData['schema:AdministrativeArea']\n ? {\n type: 'schema:AdministrativeArea',\n name: surveyData['schema:AdministrativeArea'],\n }\n : undefined;\n\n // Extract contact points from paneldynamic\n const contactPoints = extractPanelDynamicItems(surveyData, 'pannel:schema_contactPoint', (item) => {\n if (!item['schema:contactType'] && !item['schema:email'] && !item['schema:telephone']) return null;\n return {\n type: 'schema:ContactPoint',\n contactType: item['schema:contactType'] || 'general',\n email: item['schema:email'] || undefined,\n telephone: item['schema:telephone'] || undefined,\n availableLanguage: parseLanguageCodes(item['schema:availableLanguage']),\n };\n });\n\n // Build composition object\n const hasParts = extractPanelDynamicItems(surveyData, 'schema:hasPart', (item) => {\n if (!item['schema:hasPart.name'] && !item['schema:hasPart.id']) return null;\n return {\n type: 'schema:CreativeWork',\n id: item['schema:hasPart.id'] || undefined,\n name: item['schema:hasPart.name'] || undefined,\n description: item['schema:hasPart.description'] || undefined,\n url: item['schema:hasPart.url'] || undefined,\n creator: item['schema:hasPart.creator.name']\n ? {\n type: 'schema:Organization',\n name: item['schema:hasPart.creator.name'],\n }\n : undefined,\n };\n });\n\n const subjectOf = extractPanelDynamicItems(surveyData, 'schema:subjectOf', (item) => {\n if (!item['schema:subjectOf.name']) return null;\n return {\n type: 'schema:CreativeWork',\n name: item['schema:subjectOf.name'],\n url: item['schema:subjectOf.url'] || undefined,\n author: item['schema:subjectOf.author.name']\n ? {\n type: 'schema:Organisation',\n name: item['schema:subjectOf.author.name'],\n }\n : undefined,\n };\n });\n\n const composition =\n hasParts.length > 0 || subjectOf.length > 0\n ? {\n type: 'schema:Collection',\n hasPart: hasParts.length > 0 ? hasParts : undefined,\n subjectOf: subjectOf.length > 0 ? subjectOf : undefined,\n }\n : undefined;\n\n // Extract makesOffer from paneldynamic\n const makesOffer = extractPanelDynamicItems(surveyData, 'schema:makesOffer', (item) => {\n if (!item['schema:itemOffered.name']) return null;\n return {\n type: 'schema:Offer',\n itemOffered: {\n type: item['schema:itemOffered.type'] === 'service' ? 'schema:Service' : 'schema:Product',\n name: item['schema:itemOffered.name'] || undefined,\n description: item['schema:itemOffered.description'] || undefined,\n url: item['schema:itemOffered.url'] || undefined,\n },\n };\n });\n\n // Build relationships object\n const memberOf = extractPanelDynamicItems(surveyData, 'schema:memberOf', (item) => {\n if (!item['schema:memberOf.name']) return null;\n return {\n type: 'schema:Organization',\n name: item['schema:memberOf.name'],\n };\n });\n\n const wasAssociatedWith = extractPanelDynamicItems(surveyData, 'schema:wasAssociatedWith', (item) => {\n if (!item['schema:wasAssociatedWith.name']) return null;\n return {\n type: 'schema:Organization',\n name: item['schema:wasAssociatedWith.name'],\n url: item['schema:wasAssociatedWith.url'] || undefined,\n };\n });\n\n const funding = extractPanelDynamicItems(surveyData, 'schema:funding', (item) => {\n if (!item['schema:funder.name']) return null;\n return {\n type: 'schema:MonetaryGrant',\n funder: {\n type: 'schema:Organization',\n name: item['schema:funder.name'],\n },\n amount:\n item['schema:amount.value'] || item['schema:amount.currency']\n ? {\n type: 'schema:MonetaryAmount',\n currency: item['schema:amount.currency'] || 'USD',\n value: item['schema:amount.value'] || '0',\n }\n : undefined,\n };\n });\n\n const relationships =\n memberOf.length > 0 || wasAssociatedWith.length > 0 || funding.length > 0\n ? {\n memberOf: memberOf.length > 0 ? memberOf : undefined,\n 'prov:wasAssociatedWith': wasAssociatedWith.length > 0 ? wasAssociatedWith : undefined,\n funding: funding.length > 0 ? funding : undefined,\n }\n : undefined;\n\n // Extract agents from paneldynamic\n const agents = extractPanelDynamicItems(surveyData, 'ixo:agentCard', (item) => {\n if (!item['ixo:agentCard.name'] && !item['ixo:agentCard.id']) return null;\n return {\n type: 'ixo:AgentCard',\n id: item['ixo:agentCard.id'] || undefined,\n name: item['ixo:agentCard.name'] || undefined,\n description: item['ixo:agentCard.description'] || undefined,\n };\n });\n\n // Extract credentials from paneldynamic\n const credentials = extractPanelDynamicItems(surveyData, 'ixo:verifiableCredential', (item) => {\n if (!item['schema:Name'] && !item['schema:ID']) return null;\n return {\n type: 'VerifiableCredential',\n id: item['schema:ID'] || undefined,\n name: item['schema:Name'] || undefined,\n description: item['schema:description'] || undefined,\n };\n });\n\n // Extract attributes from paneldynamic\n const attributes = extractPanelDynamicItems(surveyData, 'ixo:attribute', (item) => {\n if (!item['schema:name_2']) return null;\n return {\n '@type': 'ixo:Attribute',\n '@id': item['schema:ID_2'] || `attribute:${item['schema:name_2'].replace(/\\s+/g, '_').toLowerCase()}`,\n name: item['schema:name_2'],\n value: item['schema:description_2'] || '',\n };\n });\n\n // Build project object from paneldynamic\n const projects = extractPanelDynamicItems(surveyData, 'pannel_proj:project', (item) => {\n if (!item['proj:project.name']) return null;\n\n // Extract objectives\n const objectives = extractPanelDynamicItems(item, 'proj:project.hadObjective', (objItem) => objItem['proj:hadObjective'] || null);\n\n // Extract funding\n const projectFunding = extractPanelDynamicItems(item, 'proj:wasFundedThrough', (fundItem) => ({\n type: 'proj:FundingAssociation',\n moneyAmount: fundItem['proj:moneyAmount'] || undefined,\n moneyCurrency: fundItem['proj:moneyCurrency'] || undefined,\n agent:\n fundItem['prov.agent.name'] || fundItem['prov:agent.id']\n ? {\n type: 'prov:Agent',\n id: fundItem['prov:agent.id'] || undefined,\n name: fundItem['prov.agent.name'] || undefined,\n }\n : undefined,\n }));\n\n return {\n type: 'proj:Project',\n name: item['proj:project.name'],\n description: item['proj:project.description'] || undefined,\n hadObjective: objectives.length > 0 ? objectives : undefined,\n plannedStart: item['proj:plannedStart'] || undefined,\n plannedEnd: item['proj:plannedEnd'] || undefined,\n wasFundedThrough: projectFunding.length > 0 ? projectFunding : undefined,\n };\n });\n\n // Use first project if multiple (or combine as needed)\n const project = projects.length > 0 ? projects[0] : undefined;\n\n // Build research profile\n const seedQueries = extractPanelDynamicItems(surveyData, 'ixo:ResearchProfile', (item) => item['ixo:seedQueries'] || null);\n\n const citations = extractPanelDynamicItems(surveyData, 'schema:creativeWork', (item) => {\n if (!item['schema:creativeWork.name']) return null;\n return {\n type: 'schema:CreativeWork',\n name: item['schema:creativeWork.name'],\n url: item['schema:creativeWork.url'] || undefined,\n publisher: item['schema:creativeWork.publisher'] || undefined,\n datePublished: item['schema:creativeWork.datePublished'] || undefined,\n };\n });\n\n const researchProfile =\n seedQueries.length > 0 || citations.length > 0\n ? {\n type: 'ixo:ResearchProfile',\n 'ixo:seedQueries': seedQueries.length > 0 ? seedQueries : undefined,\n citation: citations.length > 0 ? citations : undefined,\n dateModified: new Date().toISOString(),\n }\n : undefined;\n\n // Build the final credentialSubject\n const credentialSubject: DomainCardCredentialSubject = {\n id: entityDid,\n type: types.length > 0 ? types : ['ixo:dao'],\n name: surveyData['schema:name'] || '',\n description: surveyData['schema.description'] || '',\n };\n\n // Add optional fields only if they have values\n if (additionalType.length > 0) credentialSubject.additionalType = additionalType;\n if (alternateNames.length > 0) credentialSubject.alternateName = alternateNames;\n if (surveyData['schema:url']) credentialSubject.url = surveyData['schema:url'];\n if (sameAsUrls.length > 0) credentialSubject.sameAs = sameAsUrls;\n if (logo) credentialSubject.logo = logo;\n if (profileImage) credentialSubject.image = [profileImage];\n if (keywords.length > 0) credentialSubject.keywords = keywords;\n if (knowsAbout.length > 0) credentialSubject.knowsAbout = knowsAbout;\n if (address) credentialSubject.address = address;\n if (areaServed) credentialSubject.areaServed = areaServed;\n if (contactPoints.length > 0) credentialSubject.contactPoint = contactPoints;\n if (composition) credentialSubject.composition = composition;\n if (makesOffer.length > 0) credentialSubject.makesOffer = makesOffer;\n if (relationships) credentialSubject.relationships = relationships;\n if (agents.length > 0) credentialSubject.agents = agents;\n if (credentials.length > 0) credentialSubject.credentials = credentials;\n if (attributes.length > 0) credentialSubject.attributes = attributes;\n if (project) credentialSubject.project = project;\n if (researchProfile) credentialSubject.researchProfile = researchProfile;\n\n return credentialSubject;\n}\n","interface SurveyElement {\n type: string;\n name?: string;\n elements?: SurveyElement[];\n templateElements?: SurveyElement[];\n}\n\ninterface SurveyPage {\n name: string;\n elements: SurveyElement[];\n}\n\ninterface SurveyDefinition {\n pages: SurveyPage[];\n}\n\n/**\n * Recursively extracts field names from survey elements.\n * Handles nested panels and paneldynamic template elements.\n */\nfunction extractFieldsFromElements(elements: SurveyElement[], fields: Record<string, unknown>): void {\n for (const element of elements) {\n // Skip panel containers but process their children\n if (element.type === 'panel' && element.elements) {\n extractFieldsFromElements(element.elements, fields);\n continue;\n }\n\n // Handle paneldynamic - these create arrays of objects\n if (element.type === 'paneldynamic' && element.name) {\n // Initialize as empty array for dynamic panels\n fields[element.name] = [];\n\n // Also extract template element names for reference\n if (element.templateElements) {\n extractFieldsFromElements(element.templateElements, fields);\n }\n continue;\n }\n\n // Regular input elements with a name\n if (element.name && element.type !== 'panel') {\n // Set appropriate default based on type\n switch (element.type) {\n case 'boolean':\n fields[element.name] = false;\n break;\n case 'checkbox':\n fields[element.name] = [];\n break;\n case 'file':\n fields[element.name] = [];\n break;\n default:\n fields[element.name] = '';\n }\n }\n\n // Handle nested elements in regular panels\n if (element.elements) {\n extractFieldsFromElements(element.elements, fields);\n }\n }\n}\n\n/**\n * Extracts all field names from a SurveyJS survey definition\n * and creates an empty answers template object.\n *\n * This template can be used to:\n * 1. Initialize the answers prop with all possible fields\n * 2. Provide AI agents with the structure they can fill in\n *\n * @param surveyDef - The SurveyJS survey definition object\n * @returns An object with all field names as keys and empty/default values\n */\nexport function extractSurveyAnswersTemplate(surveyDef: SurveyDefinition): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n\n for (const page of surveyDef.pages) {\n extractFieldsFromElements(page.elements, fields);\n }\n\n return fields;\n}\n\n/**\n * Creates a stringified empty answers template from a survey definition.\n * Useful for initializing the block prop.\n */\nexport function createEmptyAnswersJson(surveyDef: SurveyDefinition): string {\n return JSON.stringify(extractSurveyAnswersTemplate(surveyDef));\n}\n","import { registerAction } from '../registry';\nimport { transformSurveyToCredentialSubject, buildVerifiableCredential, buildDomainCardLinkedResource } from '@/mantine/blocks/domainCreator/utils';\n\nregisterAction({\n type: 'qi/domain.create',\n can: 'domain/create',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n outputSchema: [\n { path: 'entityDid', displayName: 'Entity DID', type: 'string', description: 'The created domain entity DID' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'Blockchain transaction hash' },\n { path: 'credentialId', displayName: 'Credential ID', type: 'string', description: 'The uploaded domain card credential identifier (CID)' },\n { path: 'entityType', displayName: 'Entity Type', type: 'string', description: 'The type of domain entity created' },\n ],\n\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) throw new Error('Handlers not available');\n if (!handlers.signCredential) throw new Error('signCredential handler not implemented');\n if (!handlers.publicFileUpload) throw new Error('publicFileUpload handler not available');\n if (!handlers.createDomain) throw new Error('createDomain handler not implemented');\n if (!handlers.requestPin) throw new Error('requestPin handler not available');\n\n const configEntityType = String(inputs.entityType || 'dao').trim();\n\n let surveyData: Record<string, any> = {};\n if (inputs.surveyData) {\n if (typeof inputs.surveyData === 'string') {\n try {\n surveyData = JSON.parse(inputs.surveyData);\n } catch {\n throw new Error('surveyData must be valid JSON');\n }\n } else if (typeof inputs.surveyData === 'object' && !Array.isArray(inputs.surveyData)) {\n surveyData = inputs.surveyData as Record<string, any>;\n }\n }\n\n // Get issuer DID (user or entity)\n const issuerDid = handlers.getEntityDid?.() || handlers.getCurrentUser?.()?.address;\n if (!issuerDid) throw new Error('Unable to determine issuer DID');\n\n // Placeholder DID — createDomain returns the real one\n const entityDid = 'did:ixo:entity:pending';\n\n // Step 1: Transform survey data → W3C credentialSubject\n const credentialSubject = transformSurveyToCredentialSubject(surveyData, entityDid);\n\n // Step 2: Build unsigned verifiable credential\n const unsignedCredential = buildVerifiableCredential({\n entityDid,\n issuerDid,\n credentialSubject,\n validFrom: surveyData['schema:validFrom'] || new Date().toISOString(),\n validUntil: surveyData['schema:validUntil'],\n });\n\n // Step 3: Request PIN and sign credential\n const pin = await handlers.requestPin({\n title: 'Sign Domain Card',\n description: 'Enter your PIN to sign the Domain Card credential',\n submitText: 'Sign',\n });\n\n const { signedCredential } = await handlers.signCredential({\n issuerDid,\n issuerType: 'user',\n credential: unsignedCredential,\n pin,\n });\n\n // Step 4: Upload signed credential to Matrix/IPFS\n const credentialBlob = new Blob([JSON.stringify(signedCredential, null, 2)], {\n type: 'application/json',\n });\n const credentialFile = new File([credentialBlob], 'domainCard.json', {\n type: 'application/json',\n });\n const uploadResult = await handlers.publicFileUpload(credentialFile);\n\n // Step 5: Build LinkedResource from upload result\n const domainCardLinkedResource = buildDomainCardLinkedResource({\n entityDid,\n cid: uploadResult.cid,\n serviceEndpoint: uploadResult.url,\n description: `Domain Card for ${surveyData['schema:name'] || 'Domain'}`,\n });\n\n // Step 6: Create domain entity on chain\n const finalEntityType = surveyData['type_2'] || surveyData['daoType'] || configEntityType;\n const { entityDid: newEntityDid, transactionHash } = await handlers.createDomain({\n entityType: finalEntityType,\n linkedResource: [domainCardLinkedResource],\n startDate: surveyData['schema:validFrom'],\n endDate: surveyData['schema:validUntil'],\n });\n\n return {\n output: {\n entityDid: newEntityDid,\n transactionHash,\n credentialId: uploadResult.cid,\n entityType: finalEntityType,\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'oracle',\n can: 'oracle/query',\n sideEffect: false,\n defaultRequiresConfirmation: false,\n\n outputSchema: [{ path: 'prompt', displayName: 'Prompt', type: 'string', description: 'The prompt sent to the companion' }],\n\n run: async (inputs, ctx) => {\n const prompt = String(inputs.prompt || '').trim();\n if (!prompt) throw new Error('prompt is required');\n\n if (!ctx.handlers?.askCompanion) {\n throw new Error('askCompanion handler is not available');\n }\n\n await ctx.handlers.askCompanion(prompt);\n\n return {\n output: { prompt },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/credential.store',\n can: 'credential/store',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/execute',\n\n outputSchema: [\n { path: 'credentialKey', displayName: 'Credential Key', type: 'string', description: 'Key under which credential was stored (e.g. kycamllevel1)' },\n { path: 'cid', displayName: 'Content ID', type: 'string', description: 'IPFS-compatible CID of the credential (used for deduplication)' },\n { path: 'storedAt', displayName: 'Stored At', type: 'string', description: 'ISO timestamp of when the credential was stored' },\n { path: 'duplicate', displayName: 'Duplicate', type: 'boolean', description: 'Whether this credential was already stored (matched by CID)' },\n ],\n\n run: async (inputs, ctx) => {\n const { credential, credentialKey, roomId } = inputs;\n\n if (!credentialKey) throw new Error('credentialKey is required');\n if (!credential) throw new Error('credential is required');\n\n // Normalize credential from any AI-provided format to a plain object.\n // AI may provide: object, JSON string, or double/triple-stringified JSON.\n let parsedCredential: any = credential;\n\n if (typeof parsedCredential === 'string') {\n // Unwrap up to 3 layers of stringification\n for (let i = 0; i < 3 && typeof parsedCredential === 'string'; i++) {\n try {\n parsedCredential = JSON.parse(parsedCredential);\n } catch {\n throw new Error('credential must be a valid JSON object or JSON string');\n }\n }\n }\n\n if (typeof parsedCredential !== 'object' || parsedCredential === null || Array.isArray(parsedCredential)) {\n throw new Error('credential must be a JSON object');\n }\n\n if (!ctx.services.matrix?.storeCredential) {\n throw new Error('Matrix credential storage service not configured');\n }\n\n // Compute IPFS-compatible CID (lazy-loaded)\n const { computeJsonCID } = await import('../../../lib/cid');\n const cid = await computeJsonCID(parsedCredential);\n\n const result = await ctx.services.matrix.storeCredential({\n roomId: roomId || '',\n credentialKey: String(credentialKey),\n credential: parsedCredential,\n cid,\n });\n\n return {\n output: {\n credentialKey: String(credentialKey),\n cid,\n storedAt: result.storedAt,\n duplicate: result.duplicate,\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/payment.execute',\n can: 'payment/execute',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n outputSchema: [\n { path: 'transactionId', displayName: 'Transaction ID', type: 'string', description: 'Payment transaction identifier from the provider' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'Payment status (proposed, submitted, pending, completed, failed)' },\n { path: 'proposal', displayName: 'Proposal', type: 'object', description: 'Payment proposal object for review before execution' },\n { path: 'summary', displayName: 'Summary', type: 'object', description: 'Human-readable payment summary' },\n ],\n\n run: async (inputs, ctx) => {\n const config = inputs.paymentConfig;\n if (!config || (typeof config === 'string' && !config.trim())) {\n throw new Error('paymentConfig is required');\n }\n\n if (!ctx.handlers?.askCompanion) {\n throw new Error('askCompanion handler is not available');\n }\n\n const parsed = typeof config === 'string' ? JSON.parse(config) : config;\n const configJson = JSON.stringify(parsed, null, 2);\n\n await ctx.handlers.askCompanion(\n [\n 'Execute payment action with this configuration.',\n 'IMPORTANT: First read the flow context and settings — the flow may contain parameters required by the skill. Also review all blocks in the flow to understand the basic workflow before executing.',\n `Payment configuration JSON:\\n${configJson}`,\n ].join('\\n')\n );\n\n return {\n output: {\n status: 'requested',\n paymentConfig: parsed,\n },\n };\n },\n});\n","import { registerAction } from '../registry';\nimport { sendDirectMessage } from '../../matrixDm';\n\nregisterAction({\n type: 'qi/matrix.dm',\n can: 'matrix/dm',\n sideEffect: true,\n defaultRequiresConfirmation: false,\n\n outputSchema: [\n { path: 'roomId', displayName: 'Room ID', type: 'string', description: 'The Matrix room ID used for the DM' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'Timestamp when the message was sent' },\n ],\n\n run: async (inputs, ctx) => {\n const matrixClient = ctx.editor?.getMatrixClient?.();\n if (!matrixClient) {\n throw new Error('Matrix client not available');\n }\n\n const targetDid = String(inputs.targetDid || '').trim();\n const message = String(inputs.message || '').trim();\n\n if (!targetDid) throw new Error('Recipient DID is required');\n if (!message) throw new Error('Message is required');\n\n const result = await sendDirectMessage(matrixClient, targetDid, message);\n\n return {\n output: {\n roomId: result.roomId,\n sentAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nregisterDiffResolver('bid', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n if (!inputs.surveyStarted) return [];\n\n const collectionId = String(inputs.collectionId || '').trim();\n const role = String(inputs.role || '').trim();\n const roleLabel = role === 'evaluation_agent' || role === 'ea' ? 'Evaluator' : role ? 'Contributor' : 'Selected at runtime';\n\n return [\n {\n key: 'applicationStatus',\n label: 'Application Status',\n before: 'None',\n after: 'Pending',\n changeType: 'replace',\n severity: 'info',\n },\n {\n key: 'role',\n label: 'Role',\n before: 'None',\n after: roleLabel,\n changeType: role ? 'replace' : 'unchanged',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'surveyAnswers',\n label: 'Survey Answers',\n before: 'None',\n after: 'Submitted at runtime',\n changeType: 'replace',\n },\n ];\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nconst USDC_DENOM = 'ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B';\n\nfunction formatCoin(coin: { denom: string; amount: string }): string {\n const denom = coin.denom === USDC_DENOM ? 'USDC' : coin.denom === 'uixo' ? 'IXO' : coin.denom;\n return `${coin.amount} ${denom}`;\n}\n\nregisterDiffResolver('evaluateBid', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const bidId = String(inputs.bidId || '').trim();\n if (!bidId) return [];\n\n const decision = String(inputs.decision || '')\n .trim()\n .toLowerCase();\n const role = String(inputs.role || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const applicantDid = String(inputs.applicantDid || '').trim();\n\n const roleLower = role.toLowerCase();\n const isEvaluator = roleLower === 'evaluation_agent' || roleLower === 'ea';\n const roleLabel = isEvaluator ? 'Evaluator' : roleLower === 'service_agent' || roleLower === 'sa' ? 'Contributor' : role || 'Unknown';\n\n const isApprove = decision === 'approve';\n const isReject = decision === 'reject';\n const decisionLabel = isApprove ? 'Approve' : isReject ? 'Reject' : 'Not selected';\n const afterStatus = isApprove ? 'Approved' : isReject ? 'Rejected' : 'Pending';\n\n const results: DiffResult[] = [\n {\n key: 'bidStatus',\n label: 'Bid Status',\n before: 'Pending',\n after: afterStatus,\n changeType: decision ? 'replace' : 'unchanged',\n severity: isReject ? 'warning' : 'info',\n },\n {\n key: 'decision',\n label: 'Decision',\n before: 'None',\n after: decisionLabel,\n changeType: decision ? 'replace' : 'unchanged',\n },\n {\n key: 'applicantRole',\n label: 'Applicant Role',\n before: roleLabel,\n after: roleLabel,\n changeType: 'unchanged',\n },\n {\n key: 'bidId',\n label: 'Bid ID',\n before: bidId || 'Not selected',\n after: bidId || 'Not selected',\n changeType: 'unchanged',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n ];\n\n if (isEvaluator) {\n let amountsLabel = 'None';\n try {\n const parsed = typeof inputs.maxAmounts === 'string' ? JSON.parse(inputs.maxAmounts) : inputs.maxAmounts;\n if (Array.isArray(parsed) && parsed.length > 0) {\n amountsLabel = parsed.map((a: any) => formatCoin(a)).join(', ');\n }\n } catch {\n /* ignore */\n }\n\n results.push({\n key: 'maxAmounts',\n label: 'Max Amounts',\n before: 'None',\n after: amountsLabel,\n changeType: amountsLabel !== 'None' ? 'replace' : 'unchanged',\n });\n }\n\n if (isReject) {\n const reason = String(inputs.rejectReason || inputs.reason || '').trim();\n results.push({\n key: 'reason',\n label: 'Rejection Reason',\n before: 'None',\n after: reason || 'Not provided',\n changeType: reason ? 'replace' : 'unchanged',\n severity: 'warning',\n });\n }\n\n if (applicantDid) {\n results.push({\n key: 'applicant',\n label: 'Applicant',\n before: applicantDid,\n after: applicantDid,\n changeType: 'unchanged',\n });\n }\n\n return results;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nregisterDiffResolver('claim', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n if (!inputs.claimStarted) return [];\n\n const collectionId = String(inputs.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || '').trim();\n\n return [\n {\n key: 'claimStatus',\n label: 'Claim Status',\n before: 'None',\n after: 'Pending',\n changeType: 'replace',\n severity: 'info',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'deed',\n label: 'Deed',\n before: deedDid || 'Not configured',\n after: deedDid || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'surveyAnswers',\n label: 'Survey Answers',\n before: 'None',\n after: 'Submitted at runtime',\n changeType: 'replace',\n },\n ];\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nconst USDC_DENOM = 'ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B';\nconst DECIMALS = 6;\n\nfunction formatCoin(coin: { denom: string; amount: string }): string {\n const denom = coin.denom === USDC_DENOM ? 'USDC' : coin.denom === 'uixo' ? 'IXO' : coin.denom;\n const raw = Number(coin.amount);\n // Amounts are stored in micro-units (×10^6) — convert back to human-readable\n const display = raw >= Math.pow(10, DECIMALS) ? raw / Math.pow(10, DECIMALS) : raw;\n return `${display} ${denom}`;\n}\n\nregisterDiffResolver('evaluateClaim', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const claimId = String(inputs.claimId || '').trim();\n if (!claimId || inputs.alreadyEvaluated) return [];\n\n const decision = String(inputs.decision || '')\n .trim()\n .toLowerCase();\n const collectionId = String(inputs.collectionId || '').trim();\n const createUdid = Boolean(inputs.createUdid);\n\n const isApprove = decision === 'approve';\n const isReject = decision === 'reject';\n const decisionLabel = isApprove ? 'Approve' : isReject ? 'Reject' : 'Not selected';\n const afterStatus = isApprove ? 'Approved' : isReject ? 'Rejected' : 'Pending';\n\n const results: DiffResult[] = [\n {\n key: 'claimStatus',\n label: 'Claim Status',\n before: 'Pending',\n after: afterStatus,\n changeType: decision ? 'replace' : 'unchanged',\n severity: isReject ? 'warning' : 'info',\n },\n {\n key: 'decision',\n label: 'Decision',\n before: 'None',\n after: decisionLabel,\n changeType: decision ? 'replace' : 'unchanged',\n },\n {\n key: 'claimId',\n label: 'Claim ID',\n before: claimId || 'Not selected',\n after: claimId || 'Not selected',\n changeType: 'unchanged',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'udidProof',\n label: 'UDID Proof',\n before: 'None',\n after: createUdid ? 'Will be generated' : 'Skipped',\n changeType: createUdid ? 'replace' : 'unchanged',\n },\n ];\n\n // Show payment info if configured\n let amountsLabel = 'None';\n try {\n const raw = typeof inputs.amount === 'string' ? JSON.parse(inputs.amount) : inputs.amount;\n if (Array.isArray(raw) && raw.length > 0) {\n amountsLabel = raw.map((a: any) => formatCoin(a)).join(', ');\n } else if (raw && typeof raw === 'object' && raw.denom) {\n amountsLabel = formatCoin(raw);\n }\n } catch {\n /* ignore */\n }\n results.push({\n key: 'payment',\n label: 'Payment',\n before: 'None',\n after: amountsLabel,\n changeType: amountsLabel !== 'None' ? 'replace' : 'unchanged',\n });\n\n // Show outcome status if template exists\n if (inputs.outcomeComplete !== undefined) {\n results.push({\n key: 'outcome',\n label: 'Outcome Template',\n before: 'None',\n after: inputs.outcomeComplete ? 'Completed' : 'Not completed',\n changeType: inputs.outcomeComplete ? 'replace' : 'unchanged',\n severity: inputs.outcomeComplete ? 'info' : 'warning',\n });\n }\n\n return results;\n },\n});\n","import type { Map as YMap } from 'yjs';\nimport type { StoredDelegation } from '../types/ucan';\n\nconst ROOT_DELEGATION_KEY = '__root__';\nconst STORE_VERSION_KEY = '__version__';\nconst CURRENT_VERSION = 2;\n\n/**\n * Stored entry in Y.Map\n */\ninterface StoredEntry {\n v: number;\n data: StoredDelegation;\n}\n\n/**\n * UCAN Delegation Store — stores CAR-serialized delegations\n */\nexport interface UcanDelegationStore {\n // Core operations\n get: (cid: string) => StoredDelegation | null;\n set: (delegation: StoredDelegation) => void;\n remove: (cid: string) => void;\n has: (cid: string) => boolean;\n\n // Root management\n getRoot: () => StoredDelegation | null;\n setRootCid: (cid: string) => void;\n getRootCid: () => string | null;\n\n // Query operations\n getAll: () => StoredDelegation[];\n getByAudience: (audienceDid: string) => StoredDelegation[];\n getByIssuer: (issuerDid: string) => StoredDelegation[];\n findByCapability: (can: string, withUri: string) => StoredDelegation[];\n}\n\nconst isValidEntry = (value: unknown): value is StoredEntry => {\n if (!value || typeof value !== 'object') return false;\n const entry = value as StoredEntry;\n return entry.v === CURRENT_VERSION && entry.data !== undefined;\n};\n\nconst isReservedKey = (key: string): boolean => key === ROOT_DELEGATION_KEY || key === STORE_VERSION_KEY;\n\n/**\n * Create a UCAN delegation store backed by Y.Map\n */\nexport const createUcanDelegationStore = (yMap: YMap<unknown>): UcanDelegationStore => {\n const get = (cid: string): StoredDelegation | null => {\n if (isReservedKey(cid)) return null;\n const raw = yMap.get(cid);\n if (!raw) return null;\n if (isValidEntry(raw)) return raw.data;\n return null;\n };\n\n const set = (delegation: StoredDelegation): void => {\n const entry: StoredEntry = { v: CURRENT_VERSION, data: delegation };\n yMap.set(delegation.cid, entry);\n };\n\n const remove = (cid: string): void => {\n yMap.delete(cid);\n };\n\n const has = (cid: string): boolean => {\n return yMap.has(cid) && !isReservedKey(cid);\n };\n\n const getRoot = (): StoredDelegation | null => {\n const rootCid = yMap.get(ROOT_DELEGATION_KEY) as string | undefined;\n if (!rootCid) return null;\n return get(rootCid);\n };\n\n const setRootCid = (cid: string): void => {\n yMap.set(ROOT_DELEGATION_KEY, cid);\n };\n\n const getRootCid = (): string | null => {\n return (yMap.get(ROOT_DELEGATION_KEY) as string) || null;\n };\n\n const getAll = (): StoredDelegation[] => {\n const delegations: StoredDelegation[] = [];\n yMap.forEach((value, key) => {\n if (isReservedKey(key)) return;\n if (isValidEntry(value)) {\n delegations.push(value.data);\n }\n });\n return delegations;\n };\n\n const getByAudience = (audienceDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.audienceDid === audienceDid);\n };\n\n const getByIssuer = (issuerDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.issuerDid === issuerDid);\n };\n\n const findByCapability = (can: string, withUri: string): StoredDelegation[] => {\n return getAll().filter((d) =>\n d.capabilities.some((c) => {\n if (c.can === can && c.with === withUri) return true;\n if (c.can === '*' || c.can === 'flow/*') return true;\n if (c.can.endsWith('/*')) {\n const prefix = c.can.slice(0, -1);\n if (can.startsWith(prefix)) return true;\n }\n if (c.with === '*') return true;\n if (c.with.endsWith('*')) {\n const prefix = c.with.slice(0, -1);\n if (withUri.startsWith(prefix)) return true;\n }\n return false;\n })\n );\n };\n\n return {\n get,\n set,\n remove,\n has,\n getRoot,\n setRootCid,\n getRootCid,\n getAll,\n getByAudience,\n getByIssuer,\n findByCapability,\n };\n};\n\n/**\n * Create an in-memory UCAN delegation store (for testing)\n */\nexport const createMemoryUcanDelegationStore = (): UcanDelegationStore => {\n const store = new Map<string, unknown>();\n\n const get = (cid: string): StoredDelegation | null => {\n if (isReservedKey(cid)) return null;\n const raw = store.get(cid);\n if (!raw) return null;\n if (isValidEntry(raw)) return raw.data;\n return null;\n };\n\n const set = (delegation: StoredDelegation): void => {\n const entry: StoredEntry = { v: CURRENT_VERSION, data: delegation };\n store.set(delegation.cid, entry);\n };\n\n const remove = (cid: string): void => {\n store.delete(cid);\n };\n\n const has = (cid: string): boolean => {\n return store.has(cid) && !isReservedKey(cid);\n };\n\n const getRoot = (): StoredDelegation | null => {\n const rootCid = store.get(ROOT_DELEGATION_KEY) as string | undefined;\n if (!rootCid) return null;\n return get(rootCid);\n };\n\n const setRootCid = (cid: string): void => {\n store.set(ROOT_DELEGATION_KEY, cid);\n };\n\n const getRootCid = (): string | null => {\n return (store.get(ROOT_DELEGATION_KEY) as string) || null;\n };\n\n const getAll = (): StoredDelegation[] => {\n const delegations: StoredDelegation[] = [];\n store.forEach((value, key) => {\n if (isReservedKey(key)) return;\n if (isValidEntry(value)) {\n delegations.push(value.data);\n }\n });\n return delegations;\n };\n\n const getByAudience = (audienceDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.audienceDid === audienceDid);\n };\n\n const getByIssuer = (issuerDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.issuerDid === issuerDid);\n };\n\n const findByCapability = (can: string, withUri: string): StoredDelegation[] => {\n return getAll().filter((d) =>\n d.capabilities.some((c) => {\n if (c.can === can && c.with === withUri) return true;\n if (c.can === '*' || c.can === 'flow/*') return true;\n if (c.can.endsWith('/*')) {\n const prefix = c.can.slice(0, -1);\n if (can.startsWith(prefix)) return true;\n }\n if (c.with === '*') return true;\n if (c.with.endsWith('*')) {\n const prefix = c.with.slice(0, -1);\n if (withUri.startsWith(prefix)) return true;\n }\n return false;\n })\n );\n };\n\n return {\n get,\n set,\n remove,\n has,\n getRoot,\n setRootCid,\n getRootCid,\n getAll,\n getByAudience,\n getByIssuer,\n findByCapability,\n };\n};\n","import type { Map as YMap } from 'yjs';\nimport type { StoredInvocation } from '../types/ucan';\n\n/**\n * Invocation Store for storing and querying invocations\n *\n * Invocations are stored for:\n * - Audit trail: Cryptographic proof of who did what, when, with what authority\n * - Replay protection: Prevent same invocation being used twice\n * - Dispute resolution: Evidence if actions are contested\n * - Blockchain submission: Submit proofs to chain for immutable record\n * - Analytics: Understand flow execution patterns\n */\nexport interface InvocationStore {\n // Core operations\n add: (invocation: StoredInvocation) => void;\n get: (cid: string) => StoredInvocation | null;\n remove: (cid: string) => void;\n\n // Query operations\n getAll: () => StoredInvocation[];\n getByInvoker: (invokerDid: string) => StoredInvocation[];\n getByFlow: (flowId: string) => StoredInvocation[];\n getByBlock: (flowId: string, blockId: string) => StoredInvocation[];\n getByCapability: (can: string, withUri: string) => StoredInvocation[];\n\n // Replay protection\n hasBeenInvoked: (cid: string) => boolean;\n\n // Audit queries\n getInDateRange: (startMs: number, endMs: number) => StoredInvocation[];\n getSuccessful: () => StoredInvocation[];\n getFailures: () => StoredInvocation[];\n\n // Blockchain submission tracking\n getPendingSubmission: () => StoredInvocation[];\n markSubmitted: (cid: string, transactionHash: string) => void;\n\n // Statistics\n getCount: () => number;\n getCountByResult: () => { success: number; failure: number };\n}\n\n/**\n * Create an invocation store backed by Y.Map\n */\nexport const createInvocationStore = (yMap: YMap<unknown>): InvocationStore => {\n /**\n * Add an invocation to the store\n */\n const add = (invocation: StoredInvocation): void => {\n yMap.set(invocation.cid, invocation);\n };\n\n /**\n * Get an invocation by CID\n */\n const get = (cid: string): StoredInvocation | null => {\n const raw = yMap.get(cid);\n if (!raw || typeof raw !== 'object') return null;\n return raw as StoredInvocation;\n };\n\n /**\n * Remove an invocation (use with caution - typically invocations should be immutable)\n */\n const remove = (cid: string): void => {\n yMap.delete(cid);\n };\n\n /**\n * Get all invocations\n */\n const getAll = (): StoredInvocation[] => {\n const invocations: StoredInvocation[] = [];\n yMap.forEach((value) => {\n if (value && typeof value === 'object' && 'cid' in value) {\n invocations.push(value as StoredInvocation);\n }\n });\n // Sort by executedAt descending (most recent first)\n return invocations.sort((a, b) => b.executedAt - a.executedAt);\n };\n\n /**\n * Get invocations by invoker DID\n */\n const getByInvoker = (invokerDid: string): StoredInvocation[] => {\n return getAll().filter((i) => i.invokerDid === invokerDid);\n };\n\n /**\n * Get invocations for a specific flow\n */\n const getByFlow = (flowId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId);\n };\n\n /**\n * Get invocations for a specific block in a flow\n */\n const getByBlock = (flowId: string, blockId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId && i.blockId === blockId);\n };\n\n /**\n * Get invocations that used a specific capability\n */\n const getByCapability = (can: string, withUri: string): StoredInvocation[] => {\n return getAll().filter((i) => i.capability.can === can && i.capability.with === withUri);\n };\n\n /**\n * Check if an invocation has already been used (replay protection)\n */\n const hasBeenInvoked = (cid: string): boolean => {\n return yMap.has(cid);\n };\n\n /**\n * Get invocations in a date range\n */\n const getInDateRange = (startMs: number, endMs: number): StoredInvocation[] => {\n return getAll().filter((i) => i.executedAt >= startMs && i.executedAt <= endMs);\n };\n\n /**\n * Get successful invocations\n */\n const getSuccessful = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success');\n };\n\n /**\n * Get failed invocations\n */\n const getFailures = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'failure');\n };\n\n /**\n * Get invocations pending blockchain submission\n */\n const getPendingSubmission = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success' && !i.transactionHash);\n };\n\n /**\n * Mark an invocation as submitted to blockchain\n */\n const markSubmitted = (cid: string, transactionHash: string): void => {\n const invocation = get(cid);\n if (invocation) {\n const updated: StoredInvocation = {\n ...invocation,\n transactionHash,\n };\n yMap.set(cid, updated);\n }\n };\n\n /**\n * Get total count of invocations\n */\n const getCount = (): number => {\n return getAll().length;\n };\n\n /**\n * Get count by result type\n */\n const getCountByResult = (): { success: number; failure: number } => {\n const all = getAll();\n return {\n success: all.filter((i) => i.result === 'success').length,\n failure: all.filter((i) => i.result === 'failure').length,\n };\n };\n\n return {\n add,\n get,\n remove,\n getAll,\n getByInvoker,\n getByFlow,\n getByBlock,\n getByCapability,\n hasBeenInvoked,\n getInDateRange,\n getSuccessful,\n getFailures,\n getPendingSubmission,\n markSubmitted,\n getCount,\n getCountByResult,\n };\n};\n\n/**\n * Create an in-memory invocation store (for testing)\n */\nexport const createMemoryInvocationStore = (): InvocationStore => {\n const store = new Map<string, StoredInvocation>();\n\n const add = (invocation: StoredInvocation): void => {\n store.set(invocation.cid, invocation);\n };\n\n const get = (cid: string): StoredInvocation | null => {\n return store.get(cid) || null;\n };\n\n const remove = (cid: string): void => {\n store.delete(cid);\n };\n\n const getAll = (): StoredInvocation[] => {\n const invocations = Array.from(store.values());\n return invocations.sort((a, b) => b.executedAt - a.executedAt);\n };\n\n const getByInvoker = (invokerDid: string): StoredInvocation[] => {\n return getAll().filter((i) => i.invokerDid === invokerDid);\n };\n\n const getByFlow = (flowId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId);\n };\n\n const getByBlock = (flowId: string, blockId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId && i.blockId === blockId);\n };\n\n const getByCapability = (can: string, withUri: string): StoredInvocation[] => {\n return getAll().filter((i) => i.capability.can === can && i.capability.with === withUri);\n };\n\n const hasBeenInvoked = (cid: string): boolean => {\n return store.has(cid);\n };\n\n const getInDateRange = (startMs: number, endMs: number): StoredInvocation[] => {\n return getAll().filter((i) => i.executedAt >= startMs && i.executedAt <= endMs);\n };\n\n const getSuccessful = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success');\n };\n\n const getFailures = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'failure');\n };\n\n const getPendingSubmission = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success' && !i.transactionHash);\n };\n\n const markSubmitted = (cid: string, transactionHash: string): void => {\n const invocation = get(cid);\n if (invocation) {\n store.set(cid, { ...invocation, transactionHash });\n }\n };\n\n const getCount = (): number => {\n return store.size;\n };\n\n const getCountByResult = (): { success: number; failure: number } => {\n const all = getAll();\n return {\n success: all.filter((i) => i.result === 'success').length,\n failure: all.filter((i) => i.result === 'failure').length,\n };\n };\n\n return {\n add,\n get,\n remove,\n getAll,\n getByInvoker,\n getByFlow,\n getByBlock,\n getByCapability,\n hasBeenInvoked,\n getInDateRange,\n getSuccessful,\n getFailures,\n getPendingSubmission,\n markSubmitted,\n getCount,\n getCountByResult,\n };\n};\n","import { FlowNode, FlowNodeAuthzExtension, EvaluationStatus } from '../../types/authorization';\n\nconst parseActivationStatus = (value: unknown): EvaluationStatus | undefined => {\n if (value === 'pending' || value === 'approved' || value === 'rejected') {\n return value;\n }\n return undefined;\n};\n\nexport const buildAuthzFromProps = (props: Record<string, any>): FlowNodeAuthzExtension => {\n const activationRequiredStatus = parseActivationStatus(props.activationRequiredStatus);\n const activationUpstreamNodeId = typeof props.activationUpstreamNodeId === 'string' ? props.activationUpstreamNodeId.trim() : '';\n const linkedClaimCollectionId = typeof props.linkedClaimCollectionId === 'string' ? props.linkedClaimCollectionId.trim() : '';\n\n const authz: FlowNodeAuthzExtension = {};\n\n if (linkedClaimCollectionId) {\n authz.linkedClaim = { collectionId: linkedClaimCollectionId };\n }\n\n if (activationUpstreamNodeId && activationRequiredStatus) {\n authz.activationCondition = {\n upstreamNodeId: activationUpstreamNodeId,\n requiredStatus: activationRequiredStatus,\n requireAuthorisedActor: Boolean(props.activationRequireAuthorisedActor),\n };\n }\n\n return authz;\n};\n\nexport const buildFlowNodeFromBlock = (block: any): FlowNode => {\n const base: FlowNode = {\n id: block.id,\n type: block.type,\n props: block.props || {},\n } as FlowNode;\n\n const authz = buildAuthzFromProps(block.props || {});\n\n return {\n ...base,\n ...authz,\n };\n};\n","import type { Doc, Map as YMap } from 'yjs';\nimport type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { IxoEditorType } from '../../types/editor';\n\nexport interface FlowRuntimeStateManager {\n get: (nodeId: string) => FlowNodeRuntimeState;\n update: (nodeId: string, updates: Partial<FlowNodeRuntimeState>) => void;\n}\n\nconst ensureStateObject = (value: unknown): FlowNodeRuntimeState => {\n if (!value || typeof value !== 'object') {\n return {};\n }\n return { ...(value as FlowNodeRuntimeState) };\n};\n\nconst createYMapManager = (map: YMap<any>): FlowRuntimeStateManager => {\n return {\n get: (nodeId: string) => {\n const stored = map.get(nodeId);\n return ensureStateObject(stored);\n },\n update: (nodeId: string, updates: Partial<FlowNodeRuntimeState>) => {\n const current = ensureStateObject(map.get(nodeId));\n map.set(nodeId, { ...current, ...updates });\n },\n };\n};\n\nconst createMemoryManager = (): FlowRuntimeStateManager => {\n const memory = new Map<string, FlowNodeRuntimeState>();\n return {\n get: (nodeId: string) => ensureStateObject(memory.get(nodeId)),\n update: (nodeId: string, updates: Partial<FlowNodeRuntimeState>) => {\n const current = ensureStateObject(memory.get(nodeId));\n memory.set(nodeId, { ...current, ...updates });\n },\n };\n};\n\nexport const createRuntimeStateManager = (editor?: IxoEditorType | null): FlowRuntimeStateManager => {\n if (editor?._yRuntime) {\n return createYMapManager(editor._yRuntime);\n }\n return createMemoryManager();\n};\n\n/**\n * Clears runtime and invocations from a Y.Doc.\n * Used when cloning a flow as a template — the new document should\n * carry only configuration (intent), not execution history.\n */\nexport function clearRuntimeForTemplateClone(yDoc: Doc): void {\n const runtime = yDoc.getMap('runtime');\n const invocations = yDoc.getMap('invocations');\n\n yDoc.transact(() => {\n runtime.forEach((_, key) => runtime.delete(key));\n invocations.forEach((_, key) => invocations.delete(key));\n });\n}\n","import { FlowNode } from '../../types/authorization';\nimport type { FlowRuntimeStateManager } from './runtime';\n\nexport interface ActivationResult {\n active: boolean;\n reason?: string;\n}\n\nexport const isNodeActive = (node: FlowNode, runtime: FlowRuntimeStateManager): ActivationResult => {\n if (!node.activationCondition) {\n return { active: true };\n }\n\n const { upstreamNodeId, requiredStatus, requireAuthorisedActor } = node.activationCondition;\n if (!upstreamNodeId) {\n return { active: true };\n }\n\n const upstreamState = runtime.get(upstreamNodeId);\n if (!upstreamState.claimId) {\n return { active: false, reason: `Upstream node ${upstreamNodeId} has no claim submission yet.` };\n }\n\n if (upstreamState.evaluationStatus !== requiredStatus) {\n return {\n active: false,\n reason: `Upstream node ${upstreamNodeId} status is ${upstreamState.evaluationStatus || 'unknown'}, requires ${requiredStatus}.`,\n };\n }\n\n if (requireAuthorisedActor) {\n const upstreamActor = upstreamState.submittedByDid;\n if (!upstreamActor) {\n return { active: false, reason: 'Upstream submission actor is unknown.' };\n }\n // In UCAN-only mode, a stored invocation CID proves the actor was authorised\n if (!upstreamState.lastInvocationCid) {\n return { active: false, reason: 'Upstream execution has no invocation proof.' };\n }\n }\n\n return { active: true };\n};\n","/**\n * Flow Version Manifest\n *\n * Single source of truth for what each schema version requires.\n * Blocks and components read policy hints rather than checking version strings directly.\n */\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type FlowVersionString = '0.3' | '1.0.0';\n\nexport interface VersionPolicyUi {\n /** Show the delegation management panel in block config */\n showDelegationPanel: boolean;\n /** Show the whitelist (specific actors) option in authorization config */\n showWhitelistConfig: boolean;\n /** Show the \"anyone with flow access\" option in authorization config */\n showAnyoneConfig: boolean;\n /** Show a banner when a newer version is available */\n showMigrationBanner: boolean;\n /** Require PIN entry for block execution (invocation signing) */\n requirePinForExecution: boolean;\n}\n\nexport interface VersionPolicy {\n /** Semver-style version identifier */\n version: FlowVersionString;\n /** Human-readable label */\n label: string;\n /** Whether UCAN delegation chains are required for all executions */\n ucanRequired: boolean;\n /** Whether a root delegation must exist before any execution */\n delegationRootRequired: boolean;\n /** Whether whitelist-only authorization (no parentCapability) is acceptable */\n whitelistOnlyAllowed: boolean;\n /** Whether unrestricted access (no authorisedActors, no parentCapability) is acceptable */\n unrestrictedAllowed: boolean;\n /** Which execution path to use */\n executionPath: 'legacy' | 'invocation';\n /** Which authorization function to use */\n authorizationFn: 'v1' | 'v2';\n /** Allowed authorization modes in the UI */\n allowedAuthModes: Array<'anyone' | 'actors' | 'capability'>;\n /** UI rendering hints — blocks query these instead of checking version strings */\n ui: VersionPolicyUi;\n /** Human-readable description of this version */\n description: string;\n}\n\n// ---------------------------------------------------------------------------\n// Manifest\n// ---------------------------------------------------------------------------\n\nexport const VERSION_MANIFEST: Record<FlowVersionString, VersionPolicy> = {\n '0.3': {\n version: '0.3',\n label: 'Legacy',\n ucanRequired: false,\n delegationRootRequired: false,\n whitelistOnlyAllowed: true,\n unrestrictedAllowed: true,\n executionPath: 'legacy',\n authorizationFn: 'v1',\n allowedAuthModes: ['anyone', 'actors', 'capability'],\n ui: {\n showDelegationPanel: false,\n showWhitelistConfig: true,\n showAnyoneConfig: true,\n showMigrationBanner: true,\n requirePinForExecution: false,\n },\n description: 'Legacy version. UCAN optional, whitelist-only authorization accepted.',\n },\n '1.0.0': {\n version: '1.0.0',\n label: 'UCAN Required',\n ucanRequired: true,\n delegationRootRequired: true,\n whitelistOnlyAllowed: false,\n unrestrictedAllowed: false,\n executionPath: 'invocation',\n authorizationFn: 'v2',\n allowedAuthModes: ['capability'],\n ui: {\n showDelegationPanel: true,\n showWhitelistConfig: false,\n showAnyoneConfig: false,\n showMigrationBanner: false,\n requirePinForExecution: true,\n },\n description: 'UCAN-enforced. Every block execution requires a valid delegation chain.',\n },\n};\n\n/** The version stamped on newly created flows */\nexport const LATEST_VERSION: FlowVersionString = '1.0.0';\n\n/** Ordered migration path — each flow must step through versions sequentially */\nexport const MIGRATION_PATH: FlowVersionString[] = ['0.3', '1.0.0'];\n\n// ---------------------------------------------------------------------------\n// Utility functions\n// ---------------------------------------------------------------------------\n\n/**\n * Get the policy for a given schema version.\n * Unknown versions fall back to the strictest (latest) policy.\n */\nexport function getVersionPolicy(version: string): VersionPolicy {\n const policy = VERSION_MANIFEST[version as FlowVersionString];\n if (!policy) {\n return VERSION_MANIFEST[LATEST_VERSION];\n }\n return policy;\n}\n\n/**\n * Check whether `current` is at least `minimum` in the migration path.\n */\nexport function isVersionAtLeast(current: string, minimum: FlowVersionString): boolean {\n const currentIdx = MIGRATION_PATH.indexOf(current as FlowVersionString);\n const minimumIdx = MIGRATION_PATH.indexOf(minimum);\n // Unknown versions are treated as latest (highest index)\n const effectiveCurrent = currentIdx === -1 ? MIGRATION_PATH.length : currentIdx;\n return effectiveCurrent >= minimumIdx;\n}\n\n/**\n * Get the next version in the migration path, or null if already at latest.\n */\nexport function getNextVersion(current: string): FlowVersionString | null {\n const idx = MIGRATION_PATH.indexOf(current as FlowVersionString);\n if (idx === -1 || idx >= MIGRATION_PATH.length - 1) {\n return null;\n }\n return MIGRATION_PATH[idx + 1];\n}\n\n/**\n * Get the chain of versions needed to migrate from `from` to `to`.\n * Returns the intermediate and target versions (excludes the `from` version).\n * Returns empty array if no migration needed or path is invalid.\n */\nexport function getMigrationChain(from: string, to: string): FlowVersionString[] {\n const fromIdx = MIGRATION_PATH.indexOf(from as FlowVersionString);\n const toIdx = MIGRATION_PATH.indexOf(to as FlowVersionString);\n\n if (fromIdx === -1 || toIdx === -1 || fromIdx >= toIdx) {\n return [];\n }\n\n return MIGRATION_PATH.slice(fromIdx + 1, toIdx + 1);\n}\n","import type { UcanCapability } from '../../types/ucan';\nimport type { UcanService } from '../../services/ucanService';\nimport { getVersionPolicy } from './versionManifest';\n\nexport interface AuthorizationResult {\n authorized: boolean;\n reason?: string;\n capabilityId?: string;\n proofCids?: string[];\n}\n\n/**\n * Check if an actor is authorized to execute a block via UCAN delegation chain.\n *\n * Every execution requires a valid delegation chain from the flow owner to the actor.\n * There is no default-allow or whitelist bypass.\n *\n * For legacy flows (v0.x), UCAN delegation chain validation is skipped and execution\n * is allowed without a full proof chain.\n */\nexport const isAuthorized = async (blockId: string, actorDid: string, ucanService: UcanService, flowUri: string, schemaVersion?: string): Promise<AuthorizationResult> => {\n // If a schema version is provided, check its policy to see if UCAN is required\n if (schemaVersion) {\n const policy = getVersionPolicy(schemaVersion);\n\n if (!policy.ucanRequired) {\n // Legacy flows (v0.x) — allow execution without full UCAN delegation chain\n return { authorized: true };\n }\n }\n\n // v1.0.0+ (or no version specified): require full UCAN delegation chain\n const capability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${flowUri}:${blockId}`,\n };\n\n const result = await ucanService.validateDelegationChain(actorDid, capability);\n\n if (!result.valid) {\n return {\n authorized: false,\n reason: result.error || 'No valid capability chain found',\n };\n }\n\n const proofCids = result.proofChain?.map((d) => d.cid) || [];\n\n return {\n authorized: true,\n capabilityId: proofCids[0],\n proofCids,\n };\n};\n","import { isNodeActive } from './activation';\nimport { isAuthorized } from './authorization';\nimport { getVersionPolicy } from './versionManifest';\nimport type { FlowNode, FlowNodeRuntimeState, EvaluationStatus } from '../../types/authorization';\nimport type { FlowRuntimeStateManager } from './runtime';\nimport type { InvocationStore } from '../invocationStore';\nimport type { UcanService } from '../../services/ucanService';\nimport type { StoredInvocation, UcanCapability } from '../../types/ucan';\n\nexport interface NodeActionResult {\n claimId?: string;\n evaluationStatus?: EvaluationStatus;\n submittedByDid?: string;\n payload?: any;\n}\n\nexport interface ExecutionContext {\n runtime: FlowRuntimeStateManager;\n ucanService: UcanService;\n invocationStore: InvocationStore;\n flowUri: string;\n flowId: string;\n flowOwnerDid: string;\n now?: () => number;\n}\n\nexport interface ExecutionOutcome {\n success: boolean;\n stage: 'activation' | 'authorization' | 'claim' | 'action' | 'complete';\n error?: string;\n result?: NodeActionResult;\n capabilityId?: string;\n invocationCid?: string;\n}\n\nexport interface ExecuteNodeParams {\n node: FlowNode;\n actorDid: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n context: ExecutionContext;\n action: () => Promise<NodeActionResult>;\n pin: string;\n}\n\nconst updateRuntimeAfterSuccess = (\n node: FlowNode,\n actorDid: string,\n runtime: FlowRuntimeStateManager,\n actionResult: NodeActionResult,\n invocationCid?: string,\n now?: () => number\n) => {\n const updates: FlowNodeRuntimeState = {\n submittedByDid: actionResult.submittedByDid || actorDid,\n evaluationStatus: actionResult.evaluationStatus || 'pending',\n executionTimestamp: now ? now() : Date.now(),\n lastInvocationCid: invocationCid,\n };\n\n if (actionResult.claimId) {\n updates.claimId = actionResult.claimId;\n }\n\n runtime.update(node.id, updates);\n};\n\n/**\n * Execute a node with UCAN invocation-based authorization.\n *\n * Pipeline:\n * 1. Check activation (upstream conditions)\n * 2. Check authorization (UCAN delegation chain)\n * 3. Create invocation (signed proof of execution)\n * 4. Execute action\n * 5. Store invocation result\n * 6. Update runtime state\n */\nexport const executeNode = async ({ node, actorDid, actorType, entityRoomId, context, action, pin }: ExecuteNodeParams): Promise<ExecutionOutcome> => {\n const { runtime, ucanService, invocationStore, flowUri, flowId, now } = context;\n\n // 1. Check activation\n const activation = isNodeActive(node, runtime);\n if (!activation.active) {\n return { success: false, stage: 'activation', error: activation.reason };\n }\n\n // 2. Check authorization and get proof chain\n const auth = await isAuthorized(node.id, actorDid, ucanService, flowUri);\n if (!auth.authorized) {\n return { success: false, stage: 'authorization', error: auth.reason };\n }\n\n // 3. Check linked claim requirement\n if (node.linkedClaim && !node.linkedClaim.collectionId) {\n return { success: false, stage: 'claim', error: 'Linked claim collection is required but missing.' };\n }\n\n // 4. Create invocation BEFORE execution\n let invocationCid: string | undefined;\n let invocationData: string | undefined;\n\n if (auth.proofCids && auth.proofCids.length > 0) {\n const capability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${flowUri}:${node.id}`,\n };\n\n try {\n const invocationResult = await ucanService.createAndValidateInvocation(\n {\n invokerDid: actorDid,\n invokerType: actorType,\n entityRoomId,\n capability,\n proofs: auth.proofCids,\n pin,\n },\n flowId,\n node.id\n );\n\n if (!invocationResult.valid) {\n return {\n success: false,\n stage: 'authorization',\n error: `Invocation validation failed: ${invocationResult.error}`,\n };\n }\n\n invocationCid = invocationResult.cid;\n invocationData = invocationResult.invocation;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to create invocation';\n return { success: false, stage: 'authorization', error: message };\n }\n }\n\n // 5. Execute action\n try {\n const result = await action();\n\n // 6. Verify linked claim was provided if required\n if (node.linkedClaim && !result.claimId) {\n if (invocationStore && invocationCid && invocationData) {\n const storedInvocation: StoredInvocation = {\n cid: invocationCid,\n invocation: invocationData,\n invokerDid: actorDid,\n capability: { can: 'flow/block/execute', with: `${flowUri}:${node.id}` },\n executedAt: now ? now() : Date.now(),\n flowId,\n blockId: node.id,\n result: 'failure',\n error: 'Execution did not return a claimId for linked claim requirement.',\n proofCids: auth.proofCids || [],\n };\n invocationStore.add(storedInvocation);\n }\n\n return {\n success: false,\n stage: 'claim',\n error: 'Execution did not return a claimId for linked claim requirement.',\n invocationCid,\n };\n }\n\n // 7. Store successful invocation\n if (invocationStore && invocationCid && invocationData) {\n const storedInvocation: StoredInvocation = {\n cid: invocationCid,\n invocation: invocationData,\n invokerDid: actorDid,\n capability: { can: 'flow/block/execute', with: `${flowUri}:${node.id}` },\n executedAt: now ? now() : Date.now(),\n flowId,\n blockId: node.id,\n result: 'success',\n proofCids: auth.proofCids || [],\n claimId: result.claimId,\n };\n invocationStore.add(storedInvocation);\n }\n\n // 8. Update runtime state\n updateRuntimeAfterSuccess(node, actorDid, runtime, result, invocationCid || auth.capabilityId, now);\n\n return {\n success: true,\n stage: 'complete',\n result,\n capabilityId: auth.capabilityId,\n invocationCid,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Execution failed';\n\n // Store failed invocation\n if (invocationStore && invocationCid && invocationData) {\n const storedInvocation: StoredInvocation = {\n cid: invocationCid,\n invocation: invocationData,\n invokerDid: actorDid,\n capability: { can: 'flow/block/execute', with: `${flowUri}:${node.id}` },\n executedAt: now ? now() : Date.now(),\n flowId,\n blockId: node.id,\n result: 'failure',\n error: message,\n proofCids: auth.proofCids || [],\n };\n invocationStore.add(storedInvocation);\n }\n\n return { success: false, stage: 'action', error: message, invocationCid };\n }\n};\n\n// ---------------------------------------------------------------------------\n// Version-aware execution dispatch\n// ---------------------------------------------------------------------------\n\nexport interface ExecuteNodeVersionedParams {\n node: FlowNode;\n actorDid: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n /** Flow schema version — determines which execution path to use */\n schemaVersion: string;\n context: ExecutionContext;\n action: () => Promise<NodeActionResult>;\n /** PIN for signing invocations (required for v1.0.0+) */\n pin: string;\n}\n\n/**\n * Version-aware execution dispatch.\n * Routes to the correct execution path based on the flow's schema version.\n *\n * - v1.0.0+ → full UCAN invocation pipeline via {@link executeNode}\n * - v0.x → simplified legacy path (activation + action only, no UCAN)\n */\nexport const executeNodeVersioned = async (params: ExecuteNodeVersionedParams): Promise<ExecutionOutcome> => {\n const policy = getVersionPolicy(params.schemaVersion);\n\n if (policy.executionPath === 'invocation') {\n // v1.0.0+ — use the full UCAN invocation-based pipeline\n return executeNode({\n node: params.node,\n actorDid: params.actorDid,\n actorType: params.actorType,\n entityRoomId: params.entityRoomId,\n context: params.context,\n action: params.action,\n pin: params.pin,\n });\n }\n\n // Legacy path for v0.x flows — activation check + direct action, no UCAN\n const { node, actorDid, context, action } = params;\n const { runtime, now } = context;\n\n const activation = isNodeActive(node, runtime);\n if (!activation.active) {\n return { success: false, stage: 'activation', error: activation.reason };\n }\n\n try {\n const result = await action();\n updateRuntimeAfterSuccess(node, actorDid, runtime, result, undefined, now);\n return { success: true, stage: 'complete', result };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Execution failed';\n return { success: false, stage: 'action', error: message };\n }\n};\n","/**\n * UCAN Service using @ixo/ucan directly\n *\n * This service provides a high-level API for:\n * - Creating and managing delegations (CAR format)\n * - Creating and validating invocations\n * - Executing actions with invocation-based authorization\n *\n * The host app only needs to provide the signer (private key) after PIN decryption.\n * All UCAN operations are performed using @ixo/ucan directly.\n */\n\nimport {\n createDelegation as ucanCreateDelegation,\n createInvocation as ucanCreateInvocation,\n serializeDelegation,\n serializeInvocation,\n parseDelegation,\n parseSigner,\n signerFromMnemonic,\n type Signer,\n type Delegation,\n type Capability as UcantoCapability,\n type SupportedDID,\n} from '@ixo/ucan';\n\nimport type { UcanDelegationStore } from '../lib/ucanDelegationStore';\nimport type { InvocationStore } from '../lib/invocationStore';\nimport type {\n StoredDelegation,\n StoredInvocation,\n UcanCapability,\n InvocationResult,\n ExecutionWithInvocationResult,\n DelegationChainValidationResult,\n FindProofsResult,\n CreateRootDelegationParams,\n CreateDelegationParams,\n CreateInvocationParams,\n} from '../types/ucan';\n\n/**\n * Signer session scope type\n */\nexport type SignerSessionScope = 'session' | 'operation';\n\n/**\n * Signer session returned by createSignerSession\n */\nexport interface SignerSessionInfo {\n sessionId: string;\n did: string;\n publicKey: string;\n keyId: string;\n expiresAt: number;\n scope: SignerSessionScope;\n}\n\n/**\n * Handler functions for getting signers from the host application\n * The host app handles PIN decryption and key management\n */\nexport interface UcanServiceHandlers {\n /**\n * Get a signer for the given DID after PIN verification\n * The host app decrypts the private key using the PIN\n *\n * @returns The private key in multibase format (for parseSigner)\n * @deprecated Prefer createSignerSession for better security\n */\n getPrivateKey?: (params: { did: string; didType: 'entity' | 'user'; entityRoomId?: string; pin: string }) => Promise<string>;\n\n /**\n * Get a signer from mnemonic (alternative to getPrivateKey)\n * The host app retrieves and decrypts the mnemonic using the PIN\n *\n * @returns The mnemonic phrase\n * @deprecated Prefer createSignerSession for better security\n */\n getMnemonic?: (params: { did: string; didType: 'entity' | 'user'; entityRoomId?: string; pin: string }) => Promise<string>;\n\n // ============================================================================\n // Handle-based signer session handlers (preferred approach)\n // ============================================================================\n\n /**\n * Create a signer session that can be used for multiple sign operations.\n * The host app keeps the key material secure; the editor only receives an opaque handle.\n *\n * @param params.scope - 'session' for multiple operations, 'operation' for one-time use\n * @param params.ttlSeconds - Time-to-live for session scope (default: 300, max: 3600)\n */\n createSignerSession?: (params: {\n did: string;\n didType: 'entity' | 'user';\n entityRoomId?: string;\n pin: string;\n scope: SignerSessionScope;\n ttlSeconds?: number;\n }) => Promise<SignerSessionInfo>;\n\n /**\n * Sign data using an existing session.\n * For 'operation' scope, the session is automatically invalidated after this call.\n */\n signWithSession?: (params: { sessionId: string; data: string; algorithm?: 'Ed25519' }) => Promise<{\n signature: string;\n algorithm: 'Ed25519';\n keyId: string;\n }>;\n\n /**\n * Release a session before it expires.\n * Safe to call on already-released or expired sessions.\n */\n releaseSignerSession?: (params: { sessionId: string }) => Promise<{\n released: boolean;\n reason?: string;\n }>;\n\n // ============================================================================\n // High-level UCAN creation handlers (host creates the UCAN)\n // Use these when you want the host to handle all UCAN creation\n // ============================================================================\n\n /**\n * Create a delegation directly in the host app.\n * The host handles all signing internally using session-based signing.\n * This is the preferred approach for security.\n */\n createDelegationWithSession?: (params: {\n sessionId: string;\n audience: string;\n capabilities: Array<{\n can: string;\n with: string;\n nb?: Record<string, unknown>;\n }>;\n proofs?: string[];\n expiration?: number;\n }) => Promise<{\n cid: string;\n delegation: string;\n }>;\n\n /**\n * Create an invocation directly in the host app.\n * The host handles all signing internally using session-based signing.\n * This is the preferred approach for security.\n */\n createInvocationWithSession?: (params: {\n sessionId: string;\n audience: string;\n capability: {\n can: string;\n with: string;\n nb?: Record<string, unknown>;\n };\n proofs: string[];\n }) => Promise<{\n cid: string;\n invocation: string;\n }>;\n}\n\n/**\n * Configuration for UcanService\n */\nexport interface UcanServiceConfig {\n delegationStore: UcanDelegationStore;\n invocationStore: InvocationStore;\n handlers: UcanServiceHandlers;\n flowOwnerDid: string;\n flowUri: string;\n}\n\n/**\n * UCAN Service interface\n */\nexport interface UcanService {\n // Delegation operations\n createRootDelegation: (params: CreateRootDelegationParams) => Promise<StoredDelegation>;\n createDelegation: (params: CreateDelegationParams) => Promise<StoredDelegation>;\n revokeDelegation: (cid: string) => void;\n getDelegation: (cid: string) => StoredDelegation | null;\n getAllDelegations: () => StoredDelegation[];\n getRootDelegation: () => StoredDelegation | null;\n\n // Invocation operations\n createAndValidateInvocation: (params: CreateInvocationParams, flowId: string, blockId?: string) => Promise<InvocationResult>;\n executeWithInvocation: <T>(\n params: CreateInvocationParams,\n action: () => Promise<T>,\n flowId: string,\n blockId?: string\n ) => Promise<ExecutionWithInvocationResult & { actionResult?: T }>;\n\n // Validation\n validateDelegationChain: (audienceDid: string, capability: UcanCapability) => Promise<DelegationChainValidationResult>;\n findValidProofs: (audienceDid: string, capability: UcanCapability) => Promise<FindProofsResult>;\n\n // Parsing\n parseDelegationFromStore: (cid: string) => Promise<Delegation | null>;\n\n // Utility\n isConfigured: () => boolean;\n}\n\n/**\n * Convert a DID string to SupportedDID type (did:ixo:* or did:key:*)\n */\nfunction toSupportedDID(did: string): SupportedDID | undefined {\n if (did.startsWith('did:ixo:') || did.startsWith('did:key:')) {\n return did as SupportedDID;\n }\n return undefined;\n}\n\n/**\n * Ability type for UCAN capabilities (format: \"namespace/action\" or \"*\")\n */\ntype Ability = `${string}/${string}` | '*';\n\n/**\n * Resource type for UCAN capabilities (format: \"scheme:path\")\n */\ntype Resource = `${string}:${string}`;\n\n/**\n * Convert UcanCapability to UcantoCapability with proper type format\n * Ucanto requires `can` to be Ability and `with` to be Resource\n */\nfunction toUcantoCapabilities(capabilities: UcanCapability[]): UcantoCapability[] {\n return capabilities.map((cap) => ({\n can: cap.can as Ability,\n with: cap.with as Resource,\n ...(cap.nb && { nb: cap.nb }),\n }));\n}\n\n/**\n * Get a signer from the handlers.\n */\nasync function getSigner(handlers: UcanServiceHandlers, did: string, didType: 'entity' | 'user', entityRoomId: string | undefined, pin: string): Promise<Signer> {\n const supportedDid = toSupportedDID(did);\n\n if (handlers.getPrivateKey) {\n const privateKey = await handlers.getPrivateKey({ did, didType, entityRoomId, pin });\n return parseSigner(privateKey, supportedDid);\n }\n\n if (handlers.getMnemonic) {\n const mnemonic = await handlers.getMnemonic({ did, didType, entityRoomId, pin });\n const result = await signerFromMnemonic(mnemonic, supportedDid);\n return result.signer;\n }\n\n throw new Error('No signer handler configured (need getPrivateKey or getMnemonic)');\n}\n\n/**\n * Generate a CID-like identifier from delegation\n */\nfunction getCidFromDelegation(delegation: Delegation): string {\n return delegation.cid.toString();\n}\n\n/**\n * Create a UCAN service instance\n */\nexport const createUcanService = (config: UcanServiceConfig): UcanService => {\n const { delegationStore, invocationStore, handlers, flowOwnerDid } = config;\n\n // Cache for parsed delegations\n const delegationCache = new Map<string, Delegation>();\n\n const isConfigured = (): boolean => {\n const hasSessionHandlers = !!(handlers.createSignerSession && handlers.signWithSession);\n const hasLegacyHandlers = !!(handlers.getPrivateKey || handlers.getMnemonic);\n return hasSessionHandlers || hasLegacyHandlers;\n };\n\n const parseDelegationFromStore = async (cid: string): Promise<Delegation | null> => {\n if (delegationCache.has(cid)) {\n return delegationCache.get(cid)!;\n }\n\n const stored = delegationStore.get(cid);\n if (!stored || !stored.delegation) {\n return null;\n }\n\n try {\n const delegation = await parseDelegation(stored.delegation);\n delegationCache.set(cid, delegation);\n return delegation;\n } catch {\n return null;\n }\n };\n\n const getProofDelegations = async (proofCids: string[]): Promise<Delegation[]> => {\n const proofs: Delegation[] = [];\n for (const cid of proofCids) {\n const delegation = await parseDelegationFromStore(cid);\n if (delegation) {\n proofs.push(delegation);\n }\n }\n return proofs;\n };\n\n const createRootDelegation = async (params: CreateRootDelegationParams): Promise<StoredDelegation> => {\n const { flowOwnerDid: ownerDid, issuerType, entityRoomId, flowUri: uri, pin } = params;\n\n const signer = await getSigner(handlers, ownerDid, issuerType, entityRoomId, pin);\n\n const capabilities: UcantoCapability[] = [{ can: 'flow/*', with: uri as `${string}:${string}` }];\n\n const delegation = await ucanCreateDelegation({\n issuer: signer,\n audience: ownerDid,\n capabilities,\n proofs: [],\n });\n\n const serialized = await serializeDelegation(delegation);\n const cid = getCidFromDelegation(delegation);\n\n const storedDelegation: StoredDelegation = {\n cid,\n delegation: serialized,\n issuerDid: ownerDid,\n audienceDid: ownerDid,\n capabilities: capabilities as UcanCapability[],\n createdAt: Date.now(),\n format: 'car',\n proofCids: [],\n };\n\n delegationStore.set(storedDelegation);\n delegationStore.setRootCid(cid);\n\n delegationCache.set(cid, delegation);\n\n return storedDelegation;\n };\n\n const createDelegation = async (params: CreateDelegationParams): Promise<StoredDelegation> => {\n const { issuerDid, issuerType, entityRoomId, audience, capabilities, proofs = [], expiration, pin } = params;\n\n const signer = await getSigner(handlers, issuerDid, issuerType, entityRoomId, pin);\n\n const proofCids = proofs.length > 0 ? proofs : ([delegationStore.getRootCid()].filter(Boolean) as string[]);\n\n const proofDelegations = await getProofDelegations(proofCids);\n\n const delegation = await ucanCreateDelegation({\n issuer: signer,\n audience,\n capabilities: toUcantoCapabilities(capabilities),\n proofs: proofDelegations,\n expiration: expiration ? Math.floor(expiration / 1000) : undefined,\n });\n\n const serialized = await serializeDelegation(delegation);\n const cid = getCidFromDelegation(delegation);\n\n const storedDelegation: StoredDelegation = {\n cid,\n delegation: serialized,\n issuerDid,\n audienceDid: audience,\n capabilities,\n expiration,\n createdAt: Date.now(),\n format: 'car',\n proofCids,\n };\n\n delegationStore.set(storedDelegation);\n\n delegationCache.set(cid, delegation);\n\n return storedDelegation;\n };\n\n const revokeDelegation = (cid: string): void => {\n delegationStore.remove(cid);\n delegationCache.delete(cid);\n };\n\n const getDelegation = (cid: string): StoredDelegation | null => {\n return delegationStore.get(cid);\n };\n\n const getAllDelegations = (): StoredDelegation[] => {\n return delegationStore.getAll();\n };\n\n const getRootDelegation = (): StoredDelegation | null => {\n return delegationStore.getRoot();\n };\n\n const findValidProofs = async (audienceDid: string, capability: UcanCapability): Promise<FindProofsResult> => {\n const delegations = delegationStore.getByAudience(audienceDid);\n\n if (delegations.length === 0) {\n // Check if actor is the root audience (flow owner)\n const root = delegationStore.getRoot();\n if (root && root.audienceDid === audienceDid) {\n return { found: true, proofCids: [root.cid] };\n }\n return { found: false, error: 'No delegations found for actor' };\n }\n\n for (const delegation of delegations) {\n const covers = delegation.capabilities.some((c) => {\n if (c.can === capability.can && c.with === capability.with) return true;\n if (c.can === '*' || c.can === 'flow/*') return true;\n if (c.can.endsWith('/*')) {\n const prefix = c.can.slice(0, -1);\n if (capability.can.startsWith(prefix)) return true;\n }\n if (c.with === '*') return true;\n if (c.with.endsWith('*')) {\n const prefix = c.with.slice(0, -1);\n if (capability.with.startsWith(prefix)) return true;\n }\n return false;\n });\n\n if (covers) {\n if (delegation.expiration && delegation.expiration < Date.now()) {\n continue;\n }\n const proofCids = [delegation.cid, ...delegation.proofCids];\n return { found: true, proofCids };\n }\n }\n\n return { found: false, error: 'No valid delegation found for capability' };\n };\n\n const validateDelegationChain = async (audienceDid: string, capability: UcanCapability): Promise<DelegationChainValidationResult> => {\n const proofsResult = await findValidProofs(audienceDid, capability);\n\n if (!proofsResult.found || !proofsResult.proofCids) {\n return { valid: false, error: proofsResult.error };\n }\n\n const proofChain: StoredDelegation[] = [];\n for (const cid of proofsResult.proofCids) {\n const delegation = delegationStore.get(cid);\n if (!delegation) {\n return { valid: false, error: `Proof delegation ${cid} not found` };\n }\n proofChain.push(delegation);\n }\n\n // Validate chain integrity\n for (let i = 0; i < proofChain.length - 1; i++) {\n const current = proofChain[i];\n const parent = proofChain[i + 1];\n\n if (parent.audienceDid !== current.issuerDid) {\n return {\n valid: false,\n error: `Chain broken: ${parent.cid} audience (${parent.audienceDid}) != ${current.cid} issuer (${current.issuerDid})`,\n };\n }\n }\n\n // Validate root\n const root = proofChain[proofChain.length - 1];\n if (root.issuerDid !== flowOwnerDid) {\n return { valid: false, error: `Root issuer ${root.issuerDid} is not flow owner ${flowOwnerDid}` };\n }\n\n return { valid: true, proofChain };\n };\n\n const createAndValidateInvocation = async (params: CreateInvocationParams, _flowId: string, _blockId?: string): Promise<InvocationResult> => {\n const { invokerDid, invokerType, entityRoomId, capability, proofs, pin } = params;\n\n const validation = await validateDelegationChain(invokerDid, capability);\n if (!validation.valid) {\n return {\n cid: '',\n invocation: '',\n valid: false,\n error: validation.error,\n };\n }\n\n const signer = await getSigner(handlers, invokerDid, invokerType, entityRoomId, pin);\n const proofDelegations = await getProofDelegations(proofs);\n\n const ucantoCapability: UcantoCapability = {\n can: capability.can as Ability,\n with: capability.with as Resource,\n ...(capability.nb && { nb: capability.nb }),\n };\n\n const invocation = await ucanCreateInvocation({\n issuer: signer,\n audience: flowOwnerDid,\n capability: ucantoCapability,\n proofs: proofDelegations,\n });\n\n const serialized = await serializeInvocation(invocation);\n const built = await invocation.buildIPLDView();\n const cid = built.cid.toString();\n\n return {\n cid,\n invocation: serialized,\n valid: true,\n };\n };\n\n const executeWithInvocation = async <T>(\n params: CreateInvocationParams,\n action: () => Promise<T>,\n flowId: string,\n blockId?: string\n ): Promise<ExecutionWithInvocationResult & { actionResult?: T }> => {\n const invocationResult = await createAndValidateInvocation(params, flowId, blockId);\n\n if (!invocationResult.valid) {\n return {\n success: false,\n invocationCid: invocationResult.cid,\n error: invocationResult.error,\n };\n }\n\n if (invocationStore.hasBeenInvoked(invocationResult.cid)) {\n return {\n success: false,\n invocationCid: invocationResult.cid,\n error: 'Invocation has already been used (replay attack prevented)',\n };\n }\n\n try {\n const actionResult = await action();\n\n const storedInvocation: StoredInvocation = {\n cid: invocationResult.cid,\n invocation: invocationResult.invocation,\n invokerDid: params.invokerDid,\n capability: params.capability,\n executedAt: Date.now(),\n flowId,\n blockId,\n result: 'success',\n proofCids: params.proofs,\n };\n invocationStore.add(storedInvocation);\n\n return {\n success: true,\n invocationCid: invocationResult.cid,\n result: actionResult,\n actionResult,\n };\n } catch (error) {\n const storedInvocation: StoredInvocation = {\n cid: invocationResult.cid,\n invocation: invocationResult.invocation,\n invokerDid: params.invokerDid,\n capability: params.capability,\n executedAt: Date.now(),\n flowId,\n blockId,\n result: 'failure',\n error: error instanceof Error ? error.message : 'Unknown error',\n proofCids: params.proofs,\n };\n invocationStore.add(storedInvocation);\n\n return {\n success: false,\n invocationCid: invocationResult.cid,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n };\n\n return {\n createRootDelegation,\n createDelegation,\n revokeDelegation,\n getDelegation,\n getAllDelegations,\n getRootDelegation,\n createAndValidateInvocation,\n executeWithInvocation,\n validateDelegationChain,\n findValidProofs,\n parseDelegationFromStore,\n isConfigured,\n };\n};\n","/**\n * Flow Migration Engine\n *\n * State machine that manages per-flow version upgrades.\n * Migration progress is persisted in a Yjs map so it survives page reloads\n * and is visible to all collaborators.\n *\n * Key properties:\n * - Incremental: each work item is processed and persisted individually\n * - Resumable: interrupted migrations pick up from the last pending item\n * - Safe: version is only stamped after all items complete and post-validation passes\n * - Owner-only: only the flow owner can initiate or resume a migration\n */\n\nimport type { Map as YMap } from 'yjs';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { UcanService } from '../../services/ucanService';\nimport type { FlowVersionString } from './versionManifest';\nimport { getMigrationChain } from './versionManifest';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type MigrationPhase = 'idle' | 'analyzing' | 'ready' | 'executing' | 'validating' | 'finalizing' | 'complete' | 'failed';\n\nexport interface MigrationWorkItem {\n /** Unique identifier for this work item */\n id: string;\n /** Block ID this item relates to (empty for flow-level items like root delegation) */\n nodeId: string;\n /** Type of work to perform */\n type: 'create_root_delegation' | 'create_node_delegation' | 'backfill_capability';\n /** Current status */\n status: 'pending' | 'completed' | 'failed';\n /** Error message if failed */\n error?: string;\n /** Whether this item requires user interaction (e.g., PIN for signing) */\n requiresUserAction: boolean;\n /** Human-readable description */\n description: string;\n}\n\nexport interface MigrationState {\n /** Current phase of the migration */\n phase: MigrationPhase;\n /** Version migrating from */\n fromVersion: string;\n /** Version migrating to */\n toVersion: string;\n /** DID of the user who initiated the migration */\n initiatorDid: string;\n /** ISO timestamp when migration started */\n startedAt: string;\n /** Work items to process */\n workItems: MigrationWorkItem[];\n /** Number of completed items */\n completedItems: number;\n /** Total number of items */\n totalItems: number;\n /** Error message if migration failed */\n error?: string;\n /** ISO timestamp when migration completed */\n completedAt?: string;\n}\n\nexport interface MigrationHistoryEntry {\n from: string;\n to: string;\n migratedBy: string;\n migratedAt: string;\n itemCount: number;\n}\n\nexport interface MigrationPrecondition {\n id: string;\n description: string;\n check: (ctx: MigrationContext) => boolean | Promise<boolean>;\n /** If true, failing this precondition blocks the entire migration */\n blocking: boolean;\n}\n\nexport interface MigrationDefinition {\n from: FlowVersionString;\n to: FlowVersionString;\n\n /** Preconditions that must be met before migration can start */\n preconditions: MigrationPrecondition[];\n\n /** Analyze the flow and return work items */\n analyze: (ctx: MigrationContext) => Promise<MigrationWorkItem[]>;\n\n /** Execute a single work item */\n executeItem: (ctx: MigrationContext, item: MigrationWorkItem) => Promise<{ success: boolean; error?: string }>;\n\n /** Validate the flow after all items are processed */\n postValidate: (ctx: MigrationContext) => Promise<{ valid: boolean; errors: string[] }>;\n\n /** Finalize the migration (stamp version, update context) */\n finalize: (ctx: MigrationContext) => void;\n}\n\nexport interface MigrationContext {\n /** The editor instance */\n editor: IxoEditorType;\n /** The migration Yjs map for persisting state */\n migrationMap: YMap<any>;\n /** DID of the actor performing the migration (must be flow owner) */\n actorDid: string;\n /** DID of the flow owner */\n flowOwnerDid: string;\n /** Flow URI for capability resources */\n flowUri: string;\n /** Flow document ID */\n flowId: string;\n /** UCAN service for creating delegations */\n ucanService: UcanService;\n /** PIN for signing operations */\n pin: string;\n /** Actor type for signing */\n actorType: 'entity' | 'user';\n /** Entity room ID if signing as entity */\n entityRoomId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Migration Registry\n// ---------------------------------------------------------------------------\n\nconst MIGRATION_REGISTRY: Record<string, MigrationDefinition> = {};\n\n/**\n * Register a migration definition. Called by migration files on import.\n */\nexport function registerMigration(definition: MigrationDefinition): void {\n const key = `${definition.from}->${definition.to}`;\n MIGRATION_REGISTRY[key] = definition;\n}\n\n/**\n * Get the migration definition for a version pair.\n */\nexport function getMigrationDefinition(from: string, to: string): MigrationDefinition | null {\n return MIGRATION_REGISTRY[`${from}->${to}`] || null;\n}\n\n// ---------------------------------------------------------------------------\n// State persistence helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read the current migration state from the Yjs map.\n */\nexport function getMigrationState(migrationMap: YMap<any>): MigrationState | null {\n const raw = migrationMap.get('state');\n if (!raw) return null;\n return typeof raw === 'string' ? JSON.parse(raw) : raw;\n}\n\nfunction persistState(migrationMap: YMap<any>, state: MigrationState): void {\n migrationMap.set('state', JSON.parse(JSON.stringify(state)));\n}\n\nfunction getMigrationHistory(migrationMap: YMap<any>): MigrationHistoryEntry[] {\n const raw = migrationMap.get('history');\n if (!raw) return [];\n return typeof raw === 'string' ? JSON.parse(raw) : raw;\n}\n\nfunction appendMigrationHistory(migrationMap: YMap<any>, entry: MigrationHistoryEntry): void {\n const history = getMigrationHistory(migrationMap);\n history.push(entry);\n migrationMap.set('history', JSON.parse(JSON.stringify(history)));\n}\n\n// ---------------------------------------------------------------------------\n// Migration lifecycle functions\n// ---------------------------------------------------------------------------\n\n/**\n * Start a migration from the flow's current version to the target version.\n * Runs preconditions and analysis, persists work items.\n * Does NOT execute any items — call executeMigrationStep() for that.\n */\nexport async function startMigration(ctx: MigrationContext, fromVersion: string, toVersion: string): Promise<{ success: boolean; state: MigrationState; errors: string[] }> {\n const errors: string[] = [];\n\n // Resolve migration definition\n const definition = getMigrationDefinition(fromVersion, toVersion);\n if (!definition) {\n return {\n success: false,\n state: createFailedState(fromVersion, toVersion, ctx.actorDid, `No migration path from ${fromVersion} to ${toVersion}`),\n errors: [`No migration definition registered for ${fromVersion} -> ${toVersion}`],\n };\n }\n\n // Check preconditions\n for (const precondition of definition.preconditions) {\n const passed = await precondition.check(ctx);\n if (!passed) {\n if (precondition.blocking) {\n const state = createFailedState(fromVersion, toVersion, ctx.actorDid, `Precondition failed: ${precondition.description}`);\n persistState(ctx.migrationMap, state);\n return { success: false, state, errors: [precondition.description] };\n }\n errors.push(`Warning: ${precondition.description}`);\n }\n }\n\n // Analyze\n const workItems = await definition.analyze(ctx);\n\n const state: MigrationState = {\n phase: workItems.length === 0 ? 'ready' : 'ready',\n fromVersion,\n toVersion,\n initiatorDid: ctx.actorDid,\n startedAt: new Date().toISOString(),\n workItems,\n completedItems: 0,\n totalItems: workItems.length,\n };\n\n persistState(ctx.migrationMap, state);\n return { success: true, state, errors };\n}\n\n/**\n * Execute the next pending work item in the migration.\n * Call this repeatedly until all items are processed.\n * Returns the updated state after processing one item.\n */\nexport async function executeMigrationStep(ctx: MigrationContext): Promise<MigrationState> {\n const state = getMigrationState(ctx.migrationMap);\n if (!state) {\n throw new Error('No migration in progress');\n }\n\n if (state.phase === 'complete' || state.phase === 'failed') {\n return state;\n }\n\n const definition = getMigrationDefinition(state.fromVersion, state.toVersion);\n if (!definition) {\n state.phase = 'failed';\n state.error = `Migration definition not found for ${state.fromVersion} -> ${state.toVersion}`;\n persistState(ctx.migrationMap, state);\n return state;\n }\n\n // Find next pending item\n const pendingItem = state.workItems.find((item) => item.status === 'pending');\n if (!pendingItem) {\n // All items processed, move to validating\n state.phase = 'validating';\n persistState(ctx.migrationMap, state);\n return state;\n }\n\n // Execute the item\n state.phase = 'executing';\n persistState(ctx.migrationMap, state);\n\n const result = await definition.executeItem(ctx, pendingItem);\n\n if (result.success) {\n pendingItem.status = 'completed';\n state.completedItems++;\n } else {\n pendingItem.status = 'failed';\n pendingItem.error = result.error;\n }\n\n // Check if all items are done\n const stillPending = state.workItems.some((item) => item.status === 'pending');\n if (!stillPending) {\n const anyFailed = state.workItems.some((item) => item.status === 'failed');\n state.phase = anyFailed ? 'failed' : 'validating';\n if (anyFailed) {\n state.error = 'One or more migration items failed. Review individual items for details.';\n }\n }\n\n persistState(ctx.migrationMap, state);\n return state;\n}\n\n/**\n * Execute all remaining pending work items in sequence.\n * Convenience wrapper around executeMigrationStep.\n */\nexport async function executeAllMigrationSteps(ctx: MigrationContext): Promise<MigrationState> {\n let state = getMigrationState(ctx.migrationMap);\n if (!state) throw new Error('No migration in progress');\n\n while (state.phase !== 'validating' && state.phase !== 'failed' && state.phase !== 'complete') {\n const hasRemaining = state.workItems.some((item) => item.status === 'pending');\n if (!hasRemaining) break;\n state = await executeMigrationStep(ctx);\n }\n\n return state;\n}\n\n/**\n * Run post-validation after all work items are complete.\n * Returns validation result without modifying the version.\n */\nexport async function validateMigration(ctx: MigrationContext): Promise<{ valid: boolean; errors: string[] }> {\n const state = getMigrationState(ctx.migrationMap);\n if (!state || state.phase !== 'validating') {\n return { valid: false, errors: ['Migration is not in validating phase'] };\n }\n\n const definition = getMigrationDefinition(state.fromVersion, state.toVersion);\n if (!definition) {\n return { valid: false, errors: ['Migration definition not found'] };\n }\n\n const result = await definition.postValidate(ctx);\n\n if (!result.valid) {\n state.phase = 'failed';\n state.error = `Post-validation failed: ${result.errors.join('; ')}`;\n persistState(ctx.migrationMap, state);\n }\n\n return result;\n}\n\n/**\n * Finalize the migration — stamp the new version and record history.\n * Only call after validateMigration returns { valid: true }.\n */\nexport function finalizeMigration(ctx: MigrationContext): MigrationState {\n const state = getMigrationState(ctx.migrationMap);\n if (!state || state.phase !== 'validating') {\n throw new Error('Cannot finalize: migration is not in validating phase');\n }\n\n const definition = getMigrationDefinition(state.fromVersion, state.toVersion);\n if (!definition) {\n throw new Error('Migration definition not found');\n }\n\n // Run the definition's finalize (stamps version on root map, etc.)\n definition.finalize(ctx);\n\n // Record history\n appendMigrationHistory(ctx.migrationMap, {\n from: state.fromVersion,\n to: state.toVersion,\n migratedBy: ctx.actorDid,\n migratedAt: new Date().toISOString(),\n itemCount: state.totalItems,\n });\n\n // Update state\n state.phase = 'complete';\n state.completedAt = new Date().toISOString();\n persistState(ctx.migrationMap, state);\n\n return state;\n}\n\n/**\n * Abandon an in-progress migration. Safe because the version hasn't been bumped.\n * Resets migration state to idle.\n */\nexport function abandonMigration(migrationMap: YMap<any>): void {\n migrationMap.delete('state');\n}\n\n/**\n * Check if a migration can be resumed (has persisted state with pending items).\n */\nexport function canResumeMigration(migrationMap: YMap<any>): boolean {\n const state = getMigrationState(migrationMap);\n if (!state) return false;\n return state.phase !== 'idle' && state.phase !== 'complete' && state.phase !== 'failed';\n}\n\n/**\n * Run a full migration chain from one version to another,\n * stepping through each intermediate version.\n * For UI-driven migrations, prefer calling the individual lifecycle functions.\n */\nexport async function runMigrationChain(ctx: MigrationContext, fromVersion: string, toVersion: string): Promise<{ success: boolean; finalVersion: string; errors: string[] }> {\n const chain = getMigrationChain(fromVersion, toVersion);\n if (chain.length === 0) {\n return { success: false, finalVersion: fromVersion, errors: ['No migration path found'] };\n }\n\n let currentVersion = fromVersion;\n const allErrors: string[] = [];\n\n for (const targetVersion of chain) {\n // Start\n const startResult = await startMigration(ctx, currentVersion, targetVersion);\n if (!startResult.success) {\n return { success: false, finalVersion: currentVersion, errors: [...allErrors, ...startResult.errors] };\n }\n\n // Execute all steps\n const state = await executeAllMigrationSteps(ctx);\n if (state.phase === 'failed') {\n return { success: false, finalVersion: currentVersion, errors: [...allErrors, state.error || 'Migration failed'] };\n }\n\n // Validate\n const validation = await validateMigration(ctx);\n if (!validation.valid) {\n return { success: false, finalVersion: currentVersion, errors: [...allErrors, ...validation.errors] };\n }\n\n // Finalize\n finalizeMigration(ctx);\n currentVersion = targetVersion;\n }\n\n return { success: true, finalVersion: currentVersion, errors: allErrors };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction createFailedState(from: string, to: string, initiator: string, error: string): MigrationState {\n return {\n phase: 'failed',\n fromVersion: from,\n toVersion: to,\n initiatorDid: initiator,\n startedAt: new Date().toISOString(),\n workItems: [],\n completedItems: 0,\n totalItems: 0,\n error,\n };\n}\n","/**\n * Migration: 0.3 → 1.0.0\n *\n * Upgrades a flow from optional UCAN to required UCAN authorization.\n *\n * What this migration does:\n * 1. Creates a root delegation if one doesn't exist\n * 2. For each executable block, ensures a delegation granting\n * flow/block/execute exists in the delegation store\n * 3. Validates all delegation chains resolve back to root\n * 4. Stamps schema_version to '1.0.0'\n *\n * In v1.0.0, delegations live in the UcanDelegationStore (Yjs-backed),\n * not as block props. The authorization layer validates chains from\n * the store at execution time.\n */\n\nimport type { MigrationDefinition, MigrationContext, MigrationWorkItem } from '../migration';\nimport { registerMigration } from '../migration';\nimport type { UcanCapability } from '../../../types/ucan';\n\n/** Block types that are structural/content and don't participate in flow execution */\nconst NON_EXECUTABLE_BLOCK_TYPES = new Set(['paragraph', 'heading', 'bulletListItem', 'numberedListItem', 'image', 'table']);\n\n/**\n * Check if a delegation already exists in the store for a given block.\n */\nfunction hasDelegationForBlock(ctx: MigrationContext, blockId: string): boolean {\n const delegations = ctx.ucanService.getAllDelegations();\n const resourceUri = `${ctx.flowUri}:${blockId}`;\n return delegations.some((d) => d.capabilities.some((c) => c.can === 'flow/block/execute' && c.with === resourceUri));\n}\n\nexport const migration_0_3_to_1_0_0: MigrationDefinition = {\n from: '0.3',\n to: '1.0.0',\n\n preconditions: [\n {\n id: 'has_flow_owner',\n description: 'Flow must have a flowOwnerDid set',\n check: (ctx) => {\n const ownerDid = ctx.editor.getFlowOwnerDid?.() || ctx.flowOwnerDid;\n return !!ownerDid;\n },\n blocking: true,\n },\n {\n id: 'is_owner',\n description: 'Only the flow owner can initiate migration',\n check: (ctx) => {\n const ownerDid = ctx.editor.getFlowOwnerDid?.() || ctx.flowOwnerDid;\n return ctx.actorDid === ownerDid;\n },\n blocking: true,\n },\n {\n id: 'ucan_service_available',\n description: 'UCAN service must be configured',\n check: (ctx) => {\n return !!ctx.ucanService && ctx.ucanService.isConfigured();\n },\n blocking: true,\n },\n ],\n\n async analyze(ctx: MigrationContext): Promise<MigrationWorkItem[]> {\n const items: MigrationWorkItem[] = [];\n const blocks = ctx.editor.document;\n\n // Check if root delegation exists\n const rootDelegation = ctx.ucanService.getRootDelegation();\n if (!rootDelegation) {\n items.push({\n id: '__root_delegation__',\n nodeId: '',\n type: 'create_root_delegation',\n status: 'pending',\n requiresUserAction: true,\n description: 'Create root delegation for flow owner',\n });\n }\n\n // Scan all blocks — create delegations for executable blocks that don't have one\n if (blocks) {\n for (const block of blocks) {\n if (NON_EXECUTABLE_BLOCK_TYPES.has(block.type)) continue;\n\n if (!hasDelegationForBlock(ctx, block.id)) {\n items.push({\n id: `node_delegation_${block.id}`,\n nodeId: block.id,\n type: 'create_node_delegation',\n status: 'pending',\n requiresUserAction: true,\n description: `Create delegation for block \"${block.type}\" (${block.id})`,\n });\n }\n }\n }\n\n return items;\n },\n\n async executeItem(ctx: MigrationContext, item: MigrationWorkItem): Promise<{ success: boolean; error?: string }> {\n try {\n switch (item.type) {\n case 'create_root_delegation': {\n await ctx.ucanService.createRootDelegation({\n flowOwnerDid: ctx.flowOwnerDid,\n issuerType: ctx.actorType,\n entityRoomId: ctx.entityRoomId,\n flowUri: ctx.flowUri,\n pin: ctx.pin,\n });\n return { success: true };\n }\n\n case 'create_node_delegation':\n case 'backfill_capability': {\n // Create a delegation from flow owner granting flow/block/execute for this node\n const capability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${ctx.flowUri}:${item.nodeId}`,\n };\n\n await ctx.ucanService.createDelegation({\n issuerDid: ctx.flowOwnerDid,\n issuerType: ctx.actorType,\n entityRoomId: ctx.entityRoomId,\n audience: ctx.flowOwnerDid, // Owner delegates to self initially; actors get sub-delegations\n capabilities: [capability],\n pin: ctx.pin,\n });\n\n return { success: true };\n }\n\n default:\n return { success: false, error: `Unknown work item type: ${item.type}` };\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { success: false, error: message };\n }\n },\n\n async postValidate(ctx: MigrationContext): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n const blocks = ctx.editor.document;\n\n // Verify root delegation exists\n const rootDelegation = ctx.ucanService.getRootDelegation();\n if (!rootDelegation) {\n errors.push('Root delegation is missing after migration');\n }\n\n // Verify each executable block has a valid delegation chain\n if (blocks) {\n for (const block of blocks) {\n if (NON_EXECUTABLE_BLOCK_TYPES.has(block.type)) continue;\n\n const requiredCapability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${ctx.flowUri}:${block.id}`,\n };\n\n const validation = await ctx.ucanService.validateDelegationChain(ctx.flowOwnerDid, requiredCapability);\n if (!validation.valid) {\n errors.push(`Block \"${block.type}\" (${block.id}): delegation chain invalid — ${validation.error || 'unknown error'}`);\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n },\n\n finalize(ctx: MigrationContext): void {\n const root = ctx.editor._yRoot;\n if (!root) {\n throw new Error('Cannot finalize: editor _yRoot not available');\n }\n\n root.set('schema_version', '1.0.0');\n root.set('@context', 'https://ixo.world/flow/1.0');\n },\n};\n\n// Auto-register this migration on import\nregisterMigration(migration_0_3_to_1_0_0);\n"],"mappings":";AAEA,IAAM,UAAU,oBAAI,IAA8B;AAGlD,IAAM,sBAA8C;AAAA,EAClD,KAAK;AAAA,EACL,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,qBAAqB;AAAA,EACrB,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,SAAS;AAAA,EACT,aAAa;AACf;AAEA,IAAM,UAAU,IAAI,IAAoB,OAAO,QAAQ,mBAAmB,CAAC;AAGpE,SAAS,kBAAkB,MAAsB;AACtD,SAAO,QAAQ,IAAI,IAAI,KAAK;AAC9B;AAEO,SAAS,eAA0E,YAA6C;AACrI,UAAQ,IAAI,WAAW,MAAM,UAA8B;AAC7D;AAEO,SAAS,UAAU,MAA4C;AACpE,SAAO,QAAQ,IAAI,kBAAkB,IAAI,CAAC;AAC5C;AAEO,SAAS,gBAAoC;AAClD,SAAO,MAAM,KAAK,QAAQ,OAAO,CAAC;AACpC;AAEO,SAAS,UAAU,MAAuB;AAC/C,SAAO,QAAQ,IAAI,kBAAkB,IAAI,CAAC;AAC5C;AAGO,SAAS,eAAe,KAA2C;AACxE,aAAW,UAAU,QAAQ,OAAO,GAAG;AACrC,QAAI,OAAO,QAAQ,IAAK,QAAO;AAAA,EACjC;AACA,SAAO;AACT;;;AClDA,IAAM,cAAsC;AAAA,EAC1C,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,cAAc;AAAA,EACd,qB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