@ixo/editor 3.0.0-beta.13 → 3.0.0-beta.15
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/{capabilityValidation-BrYCMvBB.d.ts → capabilityValidation-Bnn8B_8a.d.ts} +1 -1
- package/dist/{chunk-MVIGR7ZU.mjs → chunk-UHF7YDII.mjs} +74 -1
- package/dist/chunk-UHF7YDII.mjs.map +1 -0
- package/dist/chunk-VU34HOXM.mjs +36 -0
- package/dist/chunk-VU34HOXM.mjs.map +1 -0
- package/dist/{chunk-255WVXBP.mjs → chunk-XSMXAAJC.mjs} +5552 -5276
- package/dist/chunk-XSMXAAJC.mjs.map +1 -0
- package/dist/cid-6O646X2I.mjs +9 -0
- package/dist/cid-6O646X2I.mjs.map +1 -0
- package/dist/core/index.d.ts +27 -3
- package/dist/core/index.mjs +7 -1
- package/dist/{graphql-client-DSJ3fRVn.d.ts → graphql-client-B5bA19FP.d.ts} +14 -1
- package/dist/{index-BE746hd_.d.ts → index-tyLe-Ge8.d.ts} +2 -122
- package/dist/index.d.ts +3 -3
- package/dist/index.mjs +2 -2
- package/dist/mantine/index.d.ts +9 -5
- package/dist/mantine/index.mjs +4 -2
- package/package.json +4 -1
- package/dist/chunk-255WVXBP.mjs.map +0 -1
- package/dist/chunk-MVIGR7ZU.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/lib/actionRegistry/registry.ts","../src/core/lib/actionRegistry/adapters.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.ts","../src/core/lib/actionRegistry/actions/evaluateBid.ts","../src/core/lib/actionRegistry/actions/claim.ts","../src/core/lib/actionRegistry/actions/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/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/capabilityValidation.ts","../src/core/lib/flowEngine/authorization.ts","../src/core/lib/flowEngine/executor.ts","../src/core/lib/delegationStore.ts","../src/core/services/ucanService.ts","../src/core/services/ucanManager.ts"],"sourcesContent":["import type { ActionDefinition } from './types';\n\nconst actions = new Map<string, ActionDefinition>();\n\nexport function registerAction(definition: ActionDefinition): void {\n actions.set(definition.type, definition);\n}\n\nexport function getAction(type: string): ActionDefinition | undefined {\n return actions.get(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(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 { registerAction } from '../registry';\n\nregisterAction({\n type: '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: '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: 'human.checkbox.set',\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): void {\n registerAction({\n type,\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('form.submit');\n// Backward-compatible alias for existing saved flows.\nregisterFormSubmitAction('human.form.submit');\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: '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';\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({\n type: 'bid',\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';\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({\n type: 'evaluateBid',\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';\n\nregisterAction({\n type: 'claim',\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';\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({\n type: 'evaluateClaim',\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 });\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: '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: '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: '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: '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: '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 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: '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 type { Map as YMap } from 'yjs';\nimport type { StoredDelegation } from '../types/ucan';\nimport type { SignedCapability } from '../types/capability';\n\nconst ROOT_DELEGATION_KEY = '__root__';\nconst MIGRATION_VERSION_KEY = '__version__';\nconst CURRENT_VERSION = 2;\n\n/**\n * Stored entry in Y.Map - can be either new CAR format or legacy JSON format\n */\ninterface StoredEntry {\n /** Version indicator */\n v?: number;\n /** New CAR format data */\n data?: StoredDelegation;\n /** Legacy format - raw JSON string */\n legacy?: string;\n}\n\n/**\n * UCAN Delegation Store with dual-mode support for CAR and legacy JSON formats\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 // Migration support\n getVersion: () => number;\n setVersion: (version: number) => void;\n\n // Legacy support - for backward compatibility\n getLegacy: (id: string) => SignedCapability | null;\n hasLegacy: (id: string) => boolean;\n getAllLegacy: () => SignedCapability[];\n\n // Convert legacy to new format (metadata only, CAR needs re-signing)\n convertLegacyToStored: (legacy: SignedCapability) => StoredDelegation;\n}\n\n/**\n * Check if stored value is in new format\n */\nconst isNewFormat = (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\n/**\n * Check if stored value is legacy JSON string\n */\nconst isLegacyFormat = (value: unknown): boolean => {\n return typeof value === 'string';\n};\n\n/**\n * Parse legacy JSON to SignedCapability\n */\nconst parseLegacy = (value: string): SignedCapability | null => {\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n};\n\n/**\n * Convert a legacy SignedCapability to StoredDelegation format\n * Note: This only converts the metadata. The CAR delegation field will be empty\n * as re-signing is required to produce a valid CAR.\n */\nconst legacyToStoredDelegation = (legacy: SignedCapability): StoredDelegation => {\n return {\n cid: legacy.id,\n delegation: '', // Empty - CAR requires re-signing\n issuerDid: legacy.issuer,\n audienceDid: legacy.audience,\n capabilities: legacy.capabilities.map((c) => ({\n can: c.can,\n with: c.with,\n nb: c.nb as Record<string, unknown> | undefined,\n })),\n expiration: legacy.expiration,\n createdAt: legacy.issuedAt ? new Date(legacy.issuedAt).getTime() : Date.now(),\n format: 'legacy',\n proofCids: legacy.proofs,\n };\n};\n\n/**\n * Create a UCAN delegation store backed by Y.Map with dual-mode support\n */\nexport const createUcanDelegationStore = (yMap: YMap<unknown>): UcanDelegationStore => {\n /**\n * Get a delegation by CID, handling both formats\n */\n const get = (cid: string): StoredDelegation | null => {\n if (cid === ROOT_DELEGATION_KEY || cid === MIGRATION_VERSION_KEY) return null;\n\n const raw = yMap.get(cid);\n if (!raw) return null;\n\n // New format\n if (isNewFormat(raw)) {\n return raw.data!;\n }\n\n // Legacy format\n if (isLegacyFormat(raw)) {\n const legacy = parseLegacy(raw as string);\n if (legacy) {\n return legacyToStoredDelegation(legacy);\n }\n }\n\n return null;\n };\n\n /**\n * Store a delegation in new format\n */\n const set = (delegation: StoredDelegation): void => {\n const entry: StoredEntry = {\n v: CURRENT_VERSION,\n data: delegation,\n };\n yMap.set(delegation.cid, entry);\n };\n\n /**\n * Remove a delegation\n */\n const remove = (cid: string): void => {\n yMap.delete(cid);\n };\n\n /**\n * Check if delegation exists\n */\n const has = (cid: string): boolean => {\n return yMap.has(cid) && cid !== ROOT_DELEGATION_KEY && cid !== MIGRATION_VERSION_KEY;\n };\n\n /**\n * Get root delegation\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 /**\n * Set root delegation CID\n */\n const setRootCid = (cid: string): void => {\n yMap.set(ROOT_DELEGATION_KEY, cid);\n };\n\n /**\n * Get root delegation CID\n */\n const getRootCid = (): string | null => {\n return (yMap.get(ROOT_DELEGATION_KEY) as string) || null;\n };\n\n /**\n * Get all delegations (both formats)\n */\n const getAll = (): StoredDelegation[] => {\n const delegations: StoredDelegation[] = [];\n\n yMap.forEach((value, key) => {\n if (key === ROOT_DELEGATION_KEY || key === MIGRATION_VERSION_KEY) return;\n\n // New format\n if (isNewFormat(value)) {\n delegations.push(value.data!);\n return;\n }\n\n // Legacy format\n if (isLegacyFormat(value)) {\n const legacy = parseLegacy(value as string);\n if (legacy) {\n delegations.push(legacyToStoredDelegation(legacy));\n }\n }\n });\n\n return delegations;\n };\n\n /**\n * Get delegations by audience DID\n */\n const getByAudience = (audienceDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.audienceDid === audienceDid);\n };\n\n /**\n * Get delegations by issuer DID\n */\n const getByIssuer = (issuerDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.issuerDid === issuerDid);\n };\n\n /**\n * Find delegations that grant a specific capability\n */\n const findByCapability = (can: string, withUri: string): StoredDelegation[] => {\n return getAll().filter((d) =>\n d.capabilities.some((c) => {\n // Exact match\n if (c.can === can && c.with === withUri) return true;\n\n // Wildcard matching for 'can'\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\n // Wildcard matching for 'with'\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\n return false;\n })\n );\n };\n\n /**\n * Get store version\n */\n const getVersion = (): number => {\n const version = yMap.get(MIGRATION_VERSION_KEY) as number | undefined;\n return version ?? 1;\n };\n\n /**\n * Set store version\n */\n const setVersion = (version: number): void => {\n yMap.set(MIGRATION_VERSION_KEY, version);\n };\n\n /**\n * Get legacy delegation by ID (for backward compatibility)\n */\n const getLegacy = (id: string): SignedCapability | null => {\n if (id === ROOT_DELEGATION_KEY || id === MIGRATION_VERSION_KEY) return null;\n\n const raw = yMap.get(id);\n if (!raw) return null;\n\n if (isLegacyFormat(raw)) {\n return parseLegacy(raw as string);\n }\n\n return null;\n };\n\n /**\n * Check if legacy delegation exists\n */\n const hasLegacy = (id: string): boolean => {\n if (id === ROOT_DELEGATION_KEY || id === MIGRATION_VERSION_KEY) return false;\n const raw = yMap.get(id);\n return isLegacyFormat(raw);\n };\n\n /**\n * Get all legacy delegations\n */\n const getAllLegacy = (): SignedCapability[] => {\n const legacyDelegations: SignedCapability[] = [];\n\n yMap.forEach((value, key) => {\n if (key === ROOT_DELEGATION_KEY || key === MIGRATION_VERSION_KEY) return;\n\n if (isLegacyFormat(value)) {\n const legacy = parseLegacy(value as string);\n if (legacy) {\n legacyDelegations.push(legacy);\n }\n }\n });\n\n return legacyDelegations;\n };\n\n /**\n * Convert legacy SignedCapability to StoredDelegation\n */\n const convertLegacyToStored = (legacy: SignedCapability): StoredDelegation => {\n return legacyToStoredDelegation(legacy);\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 getVersion,\n setVersion,\n getLegacy,\n hasLegacy,\n getAllLegacy,\n convertLegacyToStored,\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 (cid === ROOT_DELEGATION_KEY || cid === MIGRATION_VERSION_KEY) return null;\n\n const raw = store.get(cid);\n if (!raw) return null;\n\n if (isNewFormat(raw)) {\n return raw.data!;\n }\n\n if (isLegacyFormat(raw)) {\n const legacy = parseLegacy(raw as string);\n if (legacy) {\n return legacyToStoredDelegation(legacy);\n }\n }\n\n return null;\n };\n\n const set = (delegation: StoredDelegation): void => {\n const entry: StoredEntry = {\n v: CURRENT_VERSION,\n data: delegation,\n };\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) && cid !== ROOT_DELEGATION_KEY && cid !== MIGRATION_VERSION_KEY;\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\n store.forEach((value, key) => {\n if (key === ROOT_DELEGATION_KEY || key === MIGRATION_VERSION_KEY) return;\n\n if (isNewFormat(value)) {\n delegations.push(value.data!);\n return;\n }\n\n if (isLegacyFormat(value)) {\n const legacy = parseLegacy(value as string);\n if (legacy) {\n delegations.push(legacyToStoredDelegation(legacy));\n }\n }\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 const getVersion = (): number => {\n const version = store.get(MIGRATION_VERSION_KEY) as number | undefined;\n return version ?? 1;\n };\n\n const setVersion = (version: number): void => {\n store.set(MIGRATION_VERSION_KEY, version);\n };\n\n const getLegacy = (id: string): SignedCapability | null => {\n if (id === ROOT_DELEGATION_KEY || id === MIGRATION_VERSION_KEY) return null;\n const raw = store.get(id);\n if (!raw) return null;\n if (isLegacyFormat(raw)) {\n return parseLegacy(raw as string);\n }\n return null;\n };\n\n const hasLegacy = (id: string): boolean => {\n if (id === ROOT_DELEGATION_KEY || id === MIGRATION_VERSION_KEY) return false;\n const raw = store.get(id);\n return isLegacyFormat(raw);\n };\n\n const getAllLegacy = (): SignedCapability[] => {\n const legacyDelegations: SignedCapability[] = [];\n store.forEach((value, key) => {\n if (key === ROOT_DELEGATION_KEY || key === MIGRATION_VERSION_KEY) return;\n if (isLegacyFormat(value)) {\n const legacy = parseLegacy(value as string);\n if (legacy) {\n legacyDelegations.push(legacy);\n }\n }\n });\n return legacyDelegations;\n };\n\n const convertLegacyToStored = (legacy: SignedCapability): StoredDelegation => {\n return legacyToStoredDelegation(legacy);\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 getVersion,\n setVersion,\n getLegacy,\n hasLegacy,\n getAllLegacy,\n convertLegacyToStored,\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 parseActors = (value: unknown): string[] => {\n if (!value) return [];\n if (Array.isArray(value)) {\n return value\n .filter((item): item is string => typeof item === 'string')\n .map((item) => item.trim())\n .filter(Boolean);\n }\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (!trimmed) return [];\n try {\n const parsed = JSON.parse(trimmed);\n if (Array.isArray(parsed)) {\n return parsed\n .filter((item): item is string => typeof item === 'string')\n .map((item) => item.trim())\n .filter(Boolean);\n }\n } catch {\n // fall back to comma-separated\n }\n return trimmed\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean);\n }\n return [];\n};\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 authorisedActors = parseActors(props.authorisedActors);\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 (typeof props.parentCapability === 'string' && props.parentCapability.trim()) {\n authz.parentCapability = props.parentCapability.trim();\n }\n\n if (authorisedActors.length > 0) {\n authz.authorisedActors = authorisedActors;\n }\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 const upstreamAuthorised = Array.isArray(upstreamState.authorisedActorsSnapshot) ? (upstreamState.authorisedActorsSnapshot as string[]) : [];\n if (upstreamAuthorised.length > 0 && !upstreamAuthorised.includes(upstreamActor)) {\n return { active: false, reason: 'Upstream claim not submitted by an authorised actor.' };\n }\n }\n\n return { active: true };\n};\n","import type { SignedCapability, Capability, CapabilityValidationResult } from '../../types/capability';\nimport type { DelegationStore } from '../delegationStore';\n\ninterface ValidateChainParams {\n /** The capability to validate */\n capability: SignedCapability;\n /** The actor DID trying to use the capability */\n actorDid: string;\n /** Required capability (what the actor wants to do) */\n requiredCapability: Capability;\n /** The delegation store */\n delegationStore: DelegationStore;\n /** Handler to verify signatures */\n verifySignature: (capabilityRaw: string, issuerDid: string) => Promise<{ valid: boolean; error?: string }>;\n /** Expected root issuer (entity DID) */\n rootIssuer: string;\n}\n\n/**\n * Check if a capability grants the required permission\n */\nconst capabilityCovers = (granted: Capability, required: Capability): boolean => {\n // Check action\n if (granted.can !== required.can && granted.can !== '*') {\n // Check for wildcard patterns\n if (granted.can.endsWith('/*')) {\n const prefix = granted.can.slice(0, -2);\n if (!required.can.startsWith(prefix)) return false;\n } else {\n return false;\n }\n }\n\n // Check resource\n if (granted.with !== required.with && granted.with !== '*') {\n // Check for wildcard and prefix patterns\n if (granted.with.endsWith('/*')) {\n const prefix = granted.with.slice(0, -2);\n if (!required.with.startsWith(prefix)) return false;\n } else if (granted.with.endsWith('*')) {\n const prefix = granted.with.slice(0, -1);\n if (!required.with.startsWith(prefix)) return false;\n } else {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * Validate a capability chain back to the root\n */\nexport const validateCapabilityChain = async (params: ValidateChainParams): Promise<CapabilityValidationResult> => {\n const { capability, actorDid, requiredCapability, delegationStore, verifySignature, rootIssuer } = params;\n\n const chain: SignedCapability[] = [];\n const visited = new Set<string>();\n let current: SignedCapability | null = capability;\n\n // Walk the chain from capability back to root\n while (current) {\n // Prevent infinite loops\n if (visited.has(current.id)) {\n return { valid: false, error: 'Circular delegation detected' };\n }\n visited.add(current.id);\n chain.unshift(current);\n\n // Check expiration\n if (current.expiration && current.expiration < Date.now()) {\n return { valid: false, error: `Capability ${current.id} has expired` };\n }\n\n // Verify signature\n const signatureResult = await verifySignature(JSON.stringify(current), current.issuer);\n if (!signatureResult.valid) {\n return { valid: false, error: `Invalid signature on capability ${current.id}: ${signatureResult.error}` };\n }\n\n // If this is the root (no proofs), check issuer matches expected root authority (flow owner)\n if (current.proofs.length === 0) {\n if (current.issuer !== rootIssuer) {\n return { valid: false, error: `Root capability issuer mismatch. Expected ${rootIssuer}, got ${current.issuer}` };\n }\n break;\n }\n\n // Get parent capability\n const parentId = current.proofs[0]; // We follow the first proof\n const parent = delegationStore.get(parentId);\n if (!parent) {\n return { valid: false, error: `Parent capability ${parentId} not found` };\n }\n\n // Verify delegation chain: parent.audience must equal current.issuer\n if (parent.audience !== current.issuer) {\n return { valid: false, error: `Delegation chain broken: ${parent.audience} !== ${current.issuer}` };\n }\n\n current = parent;\n }\n\n // Verify the final capability in chain grants permission to actor\n const finalCap = chain[chain.length - 1];\n if (finalCap.audience !== actorDid) {\n return { valid: false, error: `Capability not granted to actor. Expected ${actorDid}, got ${finalCap.audience}` };\n }\n\n // Check if chain grants required capability\n // Each capability in chain must cover the required capability\n for (const cap of chain) {\n const hasRequiredCap = cap.capabilities.some((c) => capabilityCovers(c, requiredCapability));\n if (!hasRequiredCap) {\n return { valid: false, error: `Capability ${cap.id} does not grant required permission` };\n }\n }\n\n return { valid: true, chain };\n};\n\n/**\n * Find a valid capability for an actor to perform an action\n */\nexport const findValidCapability = async (params: {\n actorDid: string;\n requiredCapability: Capability;\n delegationStore: DelegationStore;\n verifySignature: (capabilityRaw: string, issuerDid: string) => Promise<{ valid: boolean; error?: string }>;\n rootIssuer: string;\n}): Promise<{ found: boolean; capabilityId?: string; error?: string }> => {\n const { actorDid, requiredCapability, delegationStore, verifySignature, rootIssuer } = params;\n\n // Get all delegations and find ones granted to this actor\n const allDelegations = delegationStore.getAll();\n const actorDelegations = allDelegations.filter((d) => d.audience === actorDid);\n\n for (const delegation of actorDelegations) {\n const result = await validateCapabilityChain({\n capability: delegation,\n actorDid,\n requiredCapability,\n delegationStore,\n verifySignature,\n rootIssuer,\n });\n\n if (result.valid) {\n return { found: true, capabilityId: delegation.id };\n }\n }\n\n // Also check if actor is the root audience (direct from entity)\n const root = delegationStore.getRoot();\n if (root && root.audience === actorDid) {\n const result = await validateCapabilityChain({\n capability: root,\n actorDid,\n requiredCapability,\n delegationStore,\n verifySignature,\n rootIssuer,\n });\n\n if (result.valid) {\n return { found: true, capabilityId: root.id };\n }\n }\n\n return { found: false, error: 'No valid capability found for actor' };\n};\n","import type { FlowNode } from '../../types/authorization';\nimport type { Capability, UcanCapability } from '../../types/capability';\nimport type { DelegationStore } from '../delegationStore';\nimport type { UCANManager, DerivedCapability } from '../../services/ucanManager';\nimport type { UcanService } from '../../services/ucanService';\nimport { findValidCapability } from './capabilityValidation';\n\nexport interface AuthorizationResult {\n authorized: boolean;\n reason?: string;\n capabilityId?: string;\n /** Proof chain CIDs for creating invocations (new @ixo/ucan) */\n proofCids?: string[];\n /** @deprecated */\n derived?: DerivedCapability;\n}\n\nexport interface AuthorizationContext {\n /** @deprecated Use delegationStore instead */\n ucanManager?: UCANManager;\n delegationStore?: DelegationStore;\n verifySignature?: (capabilityRaw: string, issuerDid: string) => Promise<{ valid: boolean; error?: string }>;\n rootIssuer?: string; // Entity DID\n flowUri?: string; // Flow resource URI\n}\n\n/**\n * Authorization context V2 for @ixo/ucan integration\n */\nexport interface AuthorizationContextV2 {\n /** UCAN service for validation (new @ixo/ucan) */\n ucanService?: UcanService;\n /** Flow URI for resource matching */\n flowUri?: string;\n /** Flow owner DID (root issuer) */\n flowOwnerDid?: string;\n\n // Legacy context (for backward compatibility)\n /** @deprecated Use ucanService instead */\n ucanManager?: UCANManager;\n /** @deprecated Use ucanService instead */\n delegationStore?: DelegationStore;\n /** @deprecated Use ucanService instead */\n verifySignature?: (capabilityRaw: string, issuerDid: string) => Promise<{ valid: boolean; error?: string }>;\n /** @deprecated Use flowOwnerDid instead */\n rootIssuer?: string;\n}\n\nexport const isActorAuthorized = async (node: FlowNode, actorDid: string, context?: AuthorizationContext): Promise<AuthorizationResult> => {\n // 1. Check authorisedActors whitelist\n if (node.authorisedActors && node.authorisedActors.length > 0) {\n if (!node.authorisedActors.includes(actorDid)) {\n return {\n authorized: false,\n reason: `Actor ${actorDid} is not in the authorized actors list for this block.`,\n };\n }\n // If in whitelist and no capability required, authorized\n if (!node.parentCapability) {\n return { authorized: true };\n }\n }\n\n // 2. Check capability chain using NEW DelegationStore approach\n if (node.parentCapability && context?.delegationStore && context?.verifySignature && context?.rootIssuer) {\n const requiredCapability: Capability = {\n can: 'flow/block/execute',\n with: context.flowUri ? `${context.flowUri}:${node.id}` : `ixo:flow:*:${node.id}`,\n };\n\n const result = await findValidCapability({\n actorDid,\n requiredCapability,\n delegationStore: context.delegationStore,\n verifySignature: context.verifySignature,\n rootIssuer: context.rootIssuer,\n });\n\n if (!result.found) {\n return {\n authorized: false,\n reason: result.error || 'No valid capability found',\n };\n }\n\n return { authorized: true, capabilityId: result.capabilityId };\n }\n\n // 3. BACKWARD COMPATIBILITY: Check capability using OLD UCANManager approach\n if (node.parentCapability && context?.ucanManager) {\n try {\n const parent = await context.ucanManager.loadParentCapability(node.parentCapability);\n const derived = await context.ucanManager.deriveNodeCapability(parent, node.id, actorDid);\n await context.ucanManager.validateDerivedCapability(derived, node.id, actorDid);\n return { authorized: true, derived };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Capability derivation failed';\n return { authorized: false, reason: message };\n }\n }\n\n // 4. If parentCapability is set but no context available\n if (node.parentCapability && !context?.delegationStore && !context?.ucanManager) {\n return {\n authorized: false,\n reason: 'Capability validation required but neither delegation store nor UCAN manager configured.',\n };\n }\n\n // 5. No restrictions = authorized\n return { authorized: true };\n};\n\n/**\n * V2 Authorization check using @ixo/ucan service\n * Returns proof chain for invocation creation\n */\nexport const isActorAuthorizedV2 = async (node: FlowNode, actorDid: string, context?: AuthorizationContextV2): Promise<AuthorizationResult> => {\n // 1. Check authorisedActors whitelist\n if (node.authorisedActors && node.authorisedActors.length > 0) {\n if (!node.authorisedActors.includes(actorDid)) {\n return {\n authorized: false,\n reason: `Actor ${actorDid} is not in the authorized actors list for this block.`,\n };\n }\n // If in whitelist and no capability required, authorized\n if (!node.parentCapability) {\n return { authorized: true };\n }\n }\n\n // 2. Check capability chain using NEW UcanService\n if (node.parentCapability && context?.ucanService && context?.flowUri) {\n const requiredCapability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${context.flowUri}:${node.id}`,\n };\n\n const validationResult = await context.ucanService.validateDelegationChain(actorDid, requiredCapability);\n\n if (!validationResult.valid) {\n return {\n authorized: false,\n reason: validationResult.error || 'No valid capability chain found',\n };\n }\n\n // Extract proof CIDs for invocation creation\n const proofCids = validationResult.proofChain?.map((d) => d.cid) || [];\n\n return {\n authorized: true,\n capabilityId: proofCids[0], // First in chain is the actor's delegation\n proofCids,\n };\n }\n\n // 3. Fallback to legacy DelegationStore approach\n if (node.parentCapability && context?.delegationStore && context?.verifySignature && context?.rootIssuer) {\n const requiredCapability: Capability = {\n can: 'flow/block/execute',\n with: context.flowUri ? `${context.flowUri}:${node.id}` : `ixo:flow:*:${node.id}`,\n };\n\n const result = await findValidCapability({\n actorDid,\n requiredCapability,\n delegationStore: context.delegationStore,\n verifySignature: context.verifySignature,\n rootIssuer: context.rootIssuer,\n });\n\n if (!result.found) {\n return {\n authorized: false,\n reason: result.error || 'No valid capability found',\n };\n }\n\n return { authorized: true, capabilityId: result.capabilityId };\n }\n\n // 4. Fallback to legacy UCANManager approach\n if (node.parentCapability && context?.ucanManager) {\n try {\n const parent = await context.ucanManager.loadParentCapability(node.parentCapability);\n const derived = await context.ucanManager.deriveNodeCapability(parent, node.id, actorDid);\n await context.ucanManager.validateDerivedCapability(derived, node.id, actorDid);\n return { authorized: true, derived };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Capability derivation failed';\n return { authorized: false, reason: message };\n }\n }\n\n // 5. If parentCapability is set but no context available\n if (node.parentCapability && !context?.ucanService && !context?.delegationStore && !context?.ucanManager) {\n return {\n authorized: false,\n reason: 'Capability validation required but no UCAN service or delegation store configured.',\n };\n }\n\n // 6. No restrictions = authorized\n return { authorized: true };\n};\n","import { isNodeActive } from './activation';\nimport { isActorAuthorized, isActorAuthorizedV2, AuthorizationContext, AuthorizationContextV2 } from './authorization';\nimport type { FlowNode, FlowNodeRuntimeState, EvaluationStatus } from '../../types/authorization';\nimport type { FlowRuntimeStateManager } from './runtime';\nimport type { DelegationStore } from '../delegationStore';\nimport type { InvocationStore } from '../invocationStore';\nimport type { UCANManager } from '../../services/ucanManager';\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 /** @deprecated Use delegationStore instead */\n ucanManager?: UCANManager;\n delegationStore?: DelegationStore;\n verifySignature?: (capabilityRaw: string, issuerDid: string) => Promise<{ valid: boolean; error?: string }>;\n rootIssuer?: string;\n flowUri?: 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 /** Invocation CID (new @ixo/ucan) */\n invocationCid?: string;\n}\n\n/**\n * V2 Execution context for @ixo/ucan integration\n */\nexport interface ExecutionContextV2 {\n runtime: FlowRuntimeStateManager;\n /** UCAN service for invocation-based execution */\n ucanService?: UcanService;\n /** Invocation store for audit trail */\n invocationStore?: InvocationStore;\n /** Flow URI */\n flowUri: string;\n /** Flow ID for invocation storage */\n flowId: string;\n /** Flow owner DID */\n flowOwnerDid: string;\n /** Current time function */\n now?: () => number;\n\n // Legacy context (for backward compatibility)\n /** @deprecated Use ucanService instead */\n ucanManager?: UCANManager;\n /** @deprecated Use ucanService instead */\n delegationStore?: DelegationStore;\n /** @deprecated Use ucanService instead */\n verifySignature?: (capabilityRaw: string, issuerDid: string) => Promise<{ valid: boolean; error?: string }>;\n /** @deprecated Use flowOwnerDid instead */\n rootIssuer?: string;\n}\n\n/**\n * V2 Execute node params with PIN for invocation signing\n */\nexport interface ExecuteNodeParamsV2 {\n node: FlowNode;\n actorDid: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n context: ExecutionContextV2;\n action: () => Promise<NodeActionResult>;\n /** PIN for signing invocation (required for @ixo/ucan) */\n pin: string;\n}\n\nexport interface ExecuteNodeParams {\n node: FlowNode;\n actorDid: string;\n context: ExecutionContext;\n action: () => Promise<NodeActionResult>;\n}\n\nconst updateRuntimeAfterSuccess = (\n node: FlowNode,\n actorDid: string,\n runtime: FlowRuntimeStateManager,\n actionResult: NodeActionResult,\n capabilityId?: 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 derivedUcan: capabilityId,\n authorisedActorsSnapshot: node.authorisedActors,\n };\n\n if (actionResult.claimId) {\n updates.claimId = actionResult.claimId;\n }\n\n runtime.update(node.id, updates);\n};\n\nexport const executeNode = async ({ node, actorDid, context, action }: ExecuteNodeParams): Promise<ExecutionOutcome> => {\n const { runtime, delegationStore, verifySignature, rootIssuer, flowUri, ucanManager, 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\n const authContext: AuthorizationContext = {\n delegationStore,\n verifySignature,\n rootIssuer,\n flowUri,\n ucanManager,\n };\n\n const auth = await isActorAuthorized(node, actorDid, authContext);\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. Execute action\n try {\n const result = await action();\n\n // 5. Verify linked claim was provided if required\n if (node.linkedClaim && !result.claimId) {\n return { success: false, stage: 'claim', error: 'Execution did not return a claimId for linked claim requirement.' };\n }\n\n // 6. Update runtime state\n updateRuntimeAfterSuccess(node, actorDid, runtime, result, auth.capabilityId, now);\n\n return { success: true, stage: 'complete', result, capabilityId: auth.capabilityId };\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/**\n * V2 Execute node with invocation-based authorization\n * Creates an invocation before execution and stores it for audit trail\n */\nexport const executeNodeWithInvocation = async ({ node, actorDid, actorType, entityRoomId, context, action, pin }: ExecuteNodeParamsV2): Promise<ExecutionOutcome> => {\n const { runtime, ucanService, invocationStore, flowUri, flowId, flowOwnerDid, 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 authContext: AuthorizationContextV2 = {\n ucanService,\n flowUri,\n flowOwnerDid,\n // Legacy fallbacks\n delegationStore: context.delegationStore,\n verifySignature: context.verifySignature,\n rootIssuer: context.rootIssuer,\n ucanManager: context.ucanManager,\n };\n\n const auth = await isActorAuthorizedV2(node, actorDid, authContext);\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 (if ucanService available)\n let invocationCid: string | undefined;\n let invocationData: string | undefined;\n\n if (ucanService && 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 // Store failed invocation if we have one\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","import type { Map as YMap } from 'yjs';\nimport type { SignedCapability } from '../types/capability';\n\nconst ROOT_CAPABILITY_KEY = '__root__';\n\nexport interface DelegationStore {\n get: (capabilityId: string) => SignedCapability | null;\n set: (capability: SignedCapability) => void;\n remove: (capabilityId: string) => void;\n getRoot: () => SignedCapability | null;\n setRootId: (capabilityId: string) => void;\n getAll: () => SignedCapability[];\n has: (capabilityId: string) => boolean;\n}\n\n/**\n * Create a delegation store backed by Y.Map\n */\nexport const createDelegationStore = (yMap: YMap<any>): DelegationStore => {\n return {\n get: (capabilityId: string): SignedCapability | null => {\n const raw = yMap.get(capabilityId);\n if (!raw || capabilityId === ROOT_CAPABILITY_KEY) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n },\n\n set: (capability: SignedCapability): void => {\n yMap.set(capability.id, JSON.stringify(capability));\n },\n\n remove: (capabilityId: string): void => {\n yMap.delete(capabilityId);\n },\n\n getRoot: (): SignedCapability | null => {\n const rootId = yMap.get(ROOT_CAPABILITY_KEY);\n if (!rootId) return null;\n const raw = yMap.get(rootId);\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n },\n\n setRootId: (capabilityId: string): void => {\n yMap.set(ROOT_CAPABILITY_KEY, capabilityId);\n },\n\n getAll: (): SignedCapability[] => {\n const capabilities: SignedCapability[] = [];\n yMap.forEach((value, key) => {\n if (key !== ROOT_CAPABILITY_KEY) {\n try {\n capabilities.push(JSON.parse(value));\n } catch {\n // Skip invalid entries\n }\n }\n });\n return capabilities;\n },\n\n has: (capabilityId: string): boolean => {\n return yMap.has(capabilityId);\n },\n };\n};\n\n/**\n * Create an in-memory delegation store (for testing or when Y.Map unavailable)\n */\nexport const createMemoryDelegationStore = (): DelegationStore => {\n const store = new Map<string, string>();\n\n return {\n get: (capabilityId: string): SignedCapability | null => {\n const raw = store.get(capabilityId);\n if (!raw || capabilityId === ROOT_CAPABILITY_KEY) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n },\n\n set: (capability: SignedCapability): void => {\n store.set(capability.id, JSON.stringify(capability));\n },\n\n remove: (capabilityId: string): void => {\n store.delete(capabilityId);\n },\n\n getRoot: (): SignedCapability | null => {\n const rootId = store.get(ROOT_CAPABILITY_KEY);\n if (!rootId) return null;\n const raw = store.get(rootId);\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n },\n\n setRootId: (capabilityId: string): void => {\n store.set(ROOT_CAPABILITY_KEY, capabilityId);\n },\n\n getAll: (): SignedCapability[] => {\n const capabilities: SignedCapability[] = [];\n store.forEach((value, key) => {\n if (key !== ROOT_CAPABILITY_KEY) {\n try {\n capabilities.push(JSON.parse(value));\n } catch {\n // Skip invalid entries\n }\n }\n });\n return capabilities;\n },\n\n has: (capabilityId: string): boolean => {\n return store.has(capabilityId);\n },\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 * - Migrating legacy delegations\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 MigrationReport,\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 // Migration\n migrateLegacyDelegation: (legacyId: string, pin: string) => Promise<StoredDelegation | null>;\n migrateAllLegacy: (pin: string) => Promise<MigrationReport>;\n getLegacyCount: () => number;\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 using legacy methods.\n * For session-based signing, use the high-level createDelegationWithSession/createInvocationWithSession handlers instead.\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 // The delegation has a cid property\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 /**\n * Check if the service is properly configured\n */\n const isConfigured = (): boolean => {\n // Prefer session-based handlers, fallback to legacy\n const hasSessionHandlers = !!(handlers.createSignerSession && handlers.signWithSession);\n const hasLegacyHandlers = !!(handlers.getPrivateKey || handlers.getMnemonic);\n return hasSessionHandlers || hasLegacyHandlers;\n };\n\n /**\n * Parse a delegation from the store and cache it\n */\n const parseDelegationFromStore = async (cid: string): Promise<Delegation | null> => {\n // Check cache first\n if (delegationCache.has(cid)) {\n return delegationCache.get(cid)!;\n }\n\n const stored = delegationStore.get(cid);\n if (!stored) return null;\n\n // If it's legacy format, we can't parse it as CAR\n if (stored.format === 'legacy' || !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 /**\n * Get proof delegations for creating invocations\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 /**\n * Create root delegation (flow owner self-issues)\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 // Cache the parsed delegation\n delegationCache.set(cid, delegation);\n\n return storedDelegation;\n };\n\n /**\n * Create a delegation\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 // Get proof CIDs - use root if no proofs provided\n const proofCids = proofs.length > 0 ? proofs : ([delegationStore.getRootCid()].filter(Boolean) as string[]);\n\n // Get proof delegations\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, // Convert ms to seconds\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 // Cache the parsed delegation\n delegationCache.set(cid, delegation);\n\n return storedDelegation;\n };\n\n /**\n * Revoke a delegation\n */\n const revokeDelegation = (cid: string): void => {\n delegationStore.remove(cid);\n delegationCache.delete(cid);\n };\n\n /**\n * Get a delegation by CID\n */\n const getDelegation = (cid: string): StoredDelegation | null => {\n return delegationStore.get(cid);\n };\n\n /**\n * Get all delegations\n */\n const getAllDelegations = (): StoredDelegation[] => {\n return delegationStore.getAll();\n };\n\n /**\n * Get root delegation\n */\n const getRootDelegation = (): StoredDelegation | null => {\n return delegationStore.getRoot();\n };\n\n /**\n * Find valid proofs for an actor to perform a capability\n */\n const findValidProofs = async (audienceDid: string, capability: UcanCapability): Promise<FindProofsResult> => {\n // Find delegations granted to this audience\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 // Find a delegation that covers the required capability\n for (const delegation of delegations) {\n const covers = delegation.capabilities.some((c) => {\n // Exact match\n if (c.can === capability.can && c.with === capability.with) return true;\n\n // Wildcard matching\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\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\n return false;\n });\n\n if (covers) {\n // Check expiration\n if (delegation.expiration && delegation.expiration < Date.now()) {\n continue; // Skip expired\n }\n\n // Build proof chain\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 /**\n * Validate a delegation chain for an actor\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 // Build the proof chain\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 // Parent audience must match current issuer\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 /**\n * Create and validate an invocation\n */\n const createAndValidateInvocation = async (params: CreateInvocationParams, _flowId: string, _blockId?: string): Promise<InvocationResult> => {\n const { invokerDid, invokerType, entityRoomId, capability, proofs, pin } = params;\n\n // Validate the actor has valid proofs\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 // Get signer\n const signer = await getSigner(handlers, invokerDid, invokerType, entityRoomId, pin);\n\n // Get proof delegations\n const proofDelegations = await getProofDelegations(proofs);\n\n // Create invocation\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\n // Get CID from 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 /**\n * Execute an action with invocation-based authorization\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 // Create and validate invocation\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 // Check replay protection\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 // Execute action\n try {\n const actionResult = await action();\n\n // Store successful invocation\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 // Store failed invocation\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 /**\n * Migrate a legacy delegation to new format\n * Note: This requires re-signing, so the original issuer must sign again\n */\n const migrateLegacyDelegation = async (legacyId: string, pin: string): Promise<StoredDelegation | null> => {\n const legacy = delegationStore.getLegacy(legacyId);\n if (!legacy) {\n return null;\n }\n\n // Create new delegation with same parameters\n const newDelegation = await createDelegation({\n issuerDid: legacy.issuer,\n issuerType: 'user', // Assume user, host app should verify\n audience: legacy.audience,\n capabilities: legacy.capabilities as UcanCapability[],\n proofs: legacy.proofs,\n expiration: legacy.expiration,\n pin,\n });\n\n return newDelegation;\n };\n\n /**\n * Migrate all legacy delegations\n */\n const migrateAllLegacy = async (pin: string): Promise<MigrationReport> => {\n const report: MigrationReport = {\n total: 0,\n migrated: 0,\n failed: 0,\n errors: [],\n };\n\n const legacyDelegations = delegationStore.getAllLegacy();\n report.total = legacyDelegations.length;\n\n for (const legacy of legacyDelegations) {\n try {\n const migrated = await migrateLegacyDelegation(legacy.id, pin);\n if (migrated) {\n report.migrated++;\n } else {\n report.failed++;\n report.errors.push({ id: legacy.id, error: 'Migration returned null' });\n }\n } catch (error) {\n report.failed++;\n report.errors.push({\n id: legacy.id,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n\n return report;\n };\n\n /**\n * Get count of legacy delegations\n */\n const getLegacyCount = (): number => {\n return delegationStore.getAllLegacy().length;\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 migrateLegacyDelegation,\n migrateAllLegacy,\n getLegacyCount,\n isConfigured,\n };\n};\n","export interface CapabilityGrant {\n raw: string;\n with?: string;\n audience?: string;\n expiresAt?: number;\n action?: string;\n}\n\nexport type DerivedCapability = CapabilityGrant;\n\nconst parseGrant = (value: string): CapabilityGrant => {\n const trimmed = value.trim();\n if (!trimmed) {\n throw new Error('Empty capability value');\n }\n\n try {\n const parsed = JSON.parse(trimmed);\n if (parsed && typeof parsed === 'object') {\n return {\n raw: trimmed,\n with: typeof parsed.with === 'string' ? parsed.with : undefined,\n audience: typeof parsed.aud === 'string' ? parsed.aud : undefined,\n expiresAt: typeof parsed.exp === 'number' ? parsed.exp * 1000 : undefined,\n action: typeof parsed.can === 'string' ? parsed.can : undefined,\n };\n }\n } catch {\n // treat as opaque string capability\n }\n\n return { raw: trimmed };\n};\n\nexport interface UCANManager {\n loadParentCapability: (capability: string) => Promise<CapabilityGrant>;\n deriveNodeCapability: (parent: CapabilityGrant, nodeId: string, actorDid: string) => Promise<DerivedCapability>;\n validateDerivedCapability: (derived: DerivedCapability, nodeId: string, actorDid: string) => Promise<void>;\n}\n\nexport class SimpleUCANManager implements UCANManager {\n async loadParentCapability(capability: string): Promise<CapabilityGrant> {\n return parseGrant(capability);\n }\n\n async deriveNodeCapability(parent: CapabilityGrant, nodeId: string, actorDid: string): Promise<DerivedCapability> {\n if (parent.expiresAt && parent.expiresAt < Date.now()) {\n throw new Error('Parent capability expired');\n }\n\n if (parent.audience && parent.audience !== actorDid) {\n throw new Error(`Actor ${actorDid} is not the audience for the capability`);\n }\n\n if (parent.with && !(parent.with.endsWith('*') || parent.with.includes(nodeId))) {\n throw new Error(`Capability resource ${parent.with} does not cover node ${nodeId}`);\n }\n\n return { ...parent };\n }\n\n async validateDerivedCapability(derived: DerivedCapability): Promise<void> {\n if (derived.expiresAt && derived.expiresAt < Date.now()) {\n throw new Error('Derived capability expired');\n }\n }\n}\n"],"mappings":";AAEA,IAAM,UAAU,oBAAI,IAA8B;AAE3C,SAAS,eAAe,YAAoC;AACjE,UAAQ,IAAI,WAAW,MAAM,UAAU;AACzC;AAEO,SAAS,UAAU,MAA4C;AACpE,SAAO,QAAQ,IAAI,IAAI;AACzB;AAEO,SAAS,gBAAoC;AAClD,SAAO,MAAM,KAAK,QAAQ,OAAO,CAAC;AACpC;AAEO,SAAS,UAAU,MAAuB;AAC/C,SAAO,QAAQ,IAAI,IAAI;AACzB;;;ACTO,SAAS,0BAA0B,UAA+B;AACvE,SAAO;AAAA,IACL,MAAM;AAAA,MACJ,SAAS,OAAO,WAAW;AACzB,cAAM,eAA4B;AAAA,UAChC,QAAQ,OAAO;AAAA,UACf,SAAS,EAAE,gBAAgB,oBAAoB,GAAG,OAAO,QAAQ;AAAA,QACnE;AACA,YAAI,OAAO,WAAW,SAAS,OAAO,MAAM;AAC1C,uBAAa,OAAO,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO,KAAK,UAAU,OAAO,IAAI;AAAA,QAChG;AACA,cAAM,MAAM,MAAM,MAAM,OAAO,KAAK,YAAY;AAChD,cAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AAC9C,cAAM,kBAA0C,CAAC;AACjD,YAAI,QAAQ,QAAQ,CAAC,OAAO,QAAQ;AAClC,0BAAgB,GAAG,IAAI;AAAA,QACzB,CAAC;AACD,eAAO;AAAA,UACL,QAAQ,IAAI;AAAA,UACZ,SAAS;AAAA,UACT;AAAA,QACF;AAAA,MACF;AAAA,IAC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QAAyB,QAAgB,UAA8C;AAChH,QAAI,OAAO,aAAa,OAAO,YAAY,KAAK,IAAI,GAAG;AACrD,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AAEA,QAAI,OAAO,YAAY,OAAO,aAAa,UAAU;AACnD,YAAM,IAAI,MAAM,SAAS,QAAQ,yCAAyC;AAAA,IAC5E;AAEA,QAAI,OAAO,QAAQ,EAAE,OAAO,KAAK,SAAS,GAAG,KAAK,OAAO,KAAK,SAAS,MAAM,IAAI;AAC/E,YAAM,IAAI,MAAM,uBAAuB,OAAO,IAAI,wBAAwB,MAAM,EAAE;AAAA,IACpF;AAEA,WAAO,EAAE,GAAG,OAAO;AAAA,EACrB;AAAA,EAEA,MAAM,0BAA0B,SAA2C;AACzE,QAAI,QAAQ,aAAa,QAAQ,YAAY,KAAK,IAAI,GAAG;AACvD,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAAA,EACF;AACF;","names":["normalizeDecision","actions"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// src/core/lib/cid.ts
|
|
2
|
+
async function computeCID(content) {
|
|
3
|
+
const { MemoryBlockstore } = await import("blockstore-core/memory");
|
|
4
|
+
const { importer } = await import("ipfs-unixfs-importer");
|
|
5
|
+
let blockstore = new MemoryBlockstore();
|
|
6
|
+
try {
|
|
7
|
+
function* singleFile() {
|
|
8
|
+
yield { path: "file", content };
|
|
9
|
+
}
|
|
10
|
+
let fileCid = null;
|
|
11
|
+
for await (const entry of importer(singleFile(), blockstore, {
|
|
12
|
+
cidVersion: 0,
|
|
13
|
+
rawLeaves: false,
|
|
14
|
+
wrapWithDirectory: false
|
|
15
|
+
})) {
|
|
16
|
+
fileCid = entry.cid.toString();
|
|
17
|
+
}
|
|
18
|
+
if (!fileCid) {
|
|
19
|
+
throw new Error("Failed to compute CID");
|
|
20
|
+
}
|
|
21
|
+
return fileCid;
|
|
22
|
+
} finally {
|
|
23
|
+
blockstore = null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
async function computeJsonCID(obj) {
|
|
27
|
+
const json = JSON.stringify(obj);
|
|
28
|
+
const encoder = new TextEncoder();
|
|
29
|
+
return computeCID(encoder.encode(json));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export {
|
|
33
|
+
computeCID,
|
|
34
|
+
computeJsonCID
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=chunk-VU34HOXM.mjs.map
|