farseer-cli 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +328 -0
  2. package/dist/commands/code.js +104 -0
  3. package/dist/commands/code.js.map +7 -0
  4. package/dist/index.js +16 -0
  5. package/dist/index.js.map +2 -2
  6. package/dist/pipeline/service.js +1 -1
  7. package/dist/pipeline/service.js.map +2 -2
  8. package/dist/services/codefirst/api.js +269 -0
  9. package/dist/services/codefirst/api.js.map +7 -0
  10. package/dist/services/codefirst/binaryDisk.js +67 -0
  11. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  12. package/dist/services/codefirst/byteHashes.js +129 -0
  13. package/dist/services/codefirst/byteHashes.js.map +7 -0
  14. package/dist/services/codefirst/documents.js +563 -0
  15. package/dist/services/codefirst/documents.js.map +7 -0
  16. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  17. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  18. package/dist/services/codefirst/layoutCompose.js +593 -0
  19. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  20. package/dist/services/codefirst/layoutCore.js +260 -0
  21. package/dist/services/codefirst/layoutCore.js.map +7 -0
  22. package/dist/services/codefirst/layoutPaths.js +492 -0
  23. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  24. package/dist/services/codefirst/layoutProjection.js +995 -0
  25. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  26. package/dist/services/codefirst/layoutReadback.js +2552 -0
  27. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  28. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  29. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  30. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  31. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  32. package/dist/services/codefirst/layoutScan.js +882 -0
  33. package/dist/services/codefirst/layoutScan.js.map +7 -0
  34. package/dist/services/codefirst/output.js +179 -0
  35. package/dist/services/codefirst/output.js.map +7 -0
  36. package/dist/services/codefirst/types.js +17 -0
  37. package/dist/services/codefirst/types.js.map +7 -0
  38. package/dist/services/codefirst/workflow.js +581 -0
  39. package/dist/services/codefirst/workflow.js.map +7 -0
  40. package/dist/services/codefirst/workspace.js +310 -0
  41. package/dist/services/codefirst/workspace.js.map +7 -0
  42. package/dist/services/codefirst/workspaceLock.js +148 -0
  43. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  44. package/dist/services/codefirst/workspaceRoot.js +147 -0
  45. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  46. package/dist/utils/logger.js +9 -3
  47. package/dist/utils/logger.js.map +2 -2
  48. package/package.json +3 -2
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/codefirst/layoutCompose.ts"],
4
+ "sourcesContent": ["/**\n * Composition: it inspects where the current workspace physically placed each resource and turns the\n * scanned artifacts into one set of semantic documents with their per-fragment observations.\n * It reads no files; layoutScan hands it everything from disk.\n */\nimport {\n AttachmentInput,\n AuthoritativeBinaryBaseline,\n BinaryFragmentRoute,\n BinarySubmissionProof,\n composeBinaryLayout,\n ComposeBinaryLayoutResult,\n DetachedFileProof,\n LayoutByteFact,\n RawFileInput,\n RawFileWireSourceMapping,\n RawShareNavigation,\n} from './layoutBinaryProjection';\nimport {\n attachmentField as ownerField,\n canonicalFragmentHash,\n clone,\n compareText,\n diagnostic as pathDiagnostic,\n FILENAME_NAME_ROLES,\n object,\n sourceFromValue,\n sourceIdentityKey,\n type JsonObject,\n} from './layoutCore';\nimport {\n encodeLayoutSegment,\n folderDirectory,\n isRawSidecarPath,\n layoutCollisionKey,\n normalizeRequiredLayoutChildren,\n parentDirectory,\n provesUnrepresentableRequest,\n type LayoutPathClaim,\n type LayoutPathRequest,\n} from './layoutPaths';\nimport {\n composeGroupedLayout,\n ComposeGroupedLayoutResult,\n DerivedSourceProof,\n ExternalGroupedOwner,\n GroupedLayoutArtifact,\n ProjectionDiagnostic,\n ProvenFragmentRoute,\n SourceIdentity,\n SubmissionCorrespondence,\n WireSourceMapping,\n} from './layoutProjection';\nimport { LayoutArtifact, LayoutScanResult, type LoadedLayoutByteEvidence } from './layoutScan';\nimport { Document, Json } from './types';\n/** One proof shape for detached documents and detached raw files; they are structurally identical. */\nexport type DetachedPlacementProof =\n | {\n reason: 'representation-fallback';\n sourceKey: string;\n request: LayoutPathRequest;\n existingClaims: readonly LayoutPathClaim[];\n inheritedFrom?: never;\n }\n | {\n reason: 'representation-fallback';\n sourceKey: string;\n request?: never;\n existingClaims?: never;\n /** Parent evidence validated by the layout submission adapter against the actual folder artifact. */\n inheritedFrom: {\n sourceKey: string;\n semanticPathHash: string;\n };\n }\n | {\n reason: 'damage-proof';\n sourceKey: string;\n placementHash: string;\n /** Canonical hash from the trusted producer that validated this placement proof. */\n baselineHash: string;\n };\n\nexport type DetachedDocumentProof = DetachedPlacementProof;\n\nexport interface CurrentLayoutPlacementInput {\n scan: LayoutScanResult;\n detachedDocumentProofs: Readonly<Record<string, DetachedDocumentProof>>;\n detachedFileProofs: Readonly<Record<string, DetachedPlacementProof>>;\n canonicalBaseline: Readonly<Record<string, string>>;\n groupedRoutes: readonly ProvenFragmentRoute[];\n groupedSources?: readonly WireSourceMapping[];\n}\n\nexport interface CurrentLayoutPlacement {\n folderNames(directory: string, diagnosticPath: string): Json[] | undefined;\n folderPlacement(semanticPath: readonly string[]): CurrentFolderPlacement | undefined;\n /**\n * Every current folder whose directory would collide with this semantic path on a filesystem\n * that folds case or normalizes Unicode. Folder paths are semantic and exact, but two of them\n * cannot share one directory, so the placement guard compares folded segments.\n */\n collidingFolderPlacements(semanticPath: readonly string[]): readonly CurrentFolderPlacement[];\n detachedDocumentValid(artifact: LayoutArtifact, value: JsonObject): boolean;\n detachedFileValid(artifact: LayoutArtifact, value: JsonObject, folder: Json): boolean;\n /** Rebind the already validated placement to the grouped sources of the same composition. */\n withGroupedSources(groupedSources: readonly WireSourceMapping[]): CurrentLayoutPlacement;\n}\n\nexport type CurrentFolderPlacement =\n | { type: 'normal'; source: SourceIdentity; semanticPath: readonly string[]; directory: string }\n | {\n type: 'detached-representation';\n source: SourceIdentity;\n semanticPath: readonly string[];\n semanticPathHash: string;\n }\n | { type: 'damaged'; source: SourceIdentity; semanticPath: readonly string[] };\n\ninterface SemanticPlacement {\n parent: string[];\n name: string;\n role: 'directory' | 'document' | 'raw';\n extension?: string;\n}\n\ninterface DetachedParentClaim {\n artifact: LayoutArtifact;\n source?: Extract<SourceIdentity, { type: 'resource' }>;\n semanticPath: string[];\n healthy: boolean;\n}\n\ntype RepresentationFallbackProof = Extract<DetachedPlacementProof, { reason: 'representation-fallback' }>;\n\nfunction sourceEquals(left: SourceIdentity, right: SourceIdentity): boolean {\n return sourceIdentityKey(left) === sourceIdentityKey(right);\n}\n\nfunction validSemanticPlacement(placement: SemanticPlacement): boolean {\n if (!placement.name || placement.parent.some((part) => !part)) return false;\n try {\n encodeLayoutSegment(placement.name);\n for (const part of placement.parent) encodeLayoutSegment(part);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction detachedDocumentPlacement(value: JsonObject): SemanticPlacement | undefined {\n if (value.kind === 'folder') {\n if (\n !Array.isArray(value.path) ||\n value.path.length === 0 ||\n value.path.some((part) => typeof part !== 'string' || part.length === 0)\n )\n return undefined;\n const names = value.path as string[];\n const placement: SemanticPlacement = {\n parent: names.slice(0, -1),\n name: names.at(-1)!,\n role: 'directory',\n };\n return validSemanticPlacement(placement) ? placement : undefined;\n }\n if (\n typeof value.kind !== 'string' ||\n !['variable', 'dimension_table', 'sheet', 'dashboard', 'remote_job'].includes(value.kind) ||\n typeof value.name !== 'string' ||\n value.name.length === 0 ||\n !Array.isArray(value.folder) ||\n value.folder.some((part) => typeof part !== 'string' || part.length === 0)\n )\n return undefined;\n const placement: SemanticPlacement = {\n parent: value.folder as string[],\n name: value.name,\n extension: '.json',\n role: 'document',\n };\n return validSemanticPlacement(placement) ? placement : undefined;\n}\n\nfunction rawPlacement(name: string, folder: Json): SemanticPlacement | undefined {\n if (!Array.isArray(folder) || folder.some((part) => typeof part !== 'string' || part.length === 0))\n return undefined;\n const placement: SemanticPlacement = { parent: folder as string[], name, role: 'raw' };\n return validSemanticPlacement(placement) ? placement : undefined;\n}\n\nfunction placementRequest(placement: SemanticPlacement, identity: string, directory: string): LayoutPathRequest {\n return {\n directory,\n name: placement.name,\n ...(placement.extension ? { extension: placement.extension } : {}),\n role: placement.role,\n identity,\n ...(placement.role === 'directory' ? { requiredChildren: ['_folder.json'] as const } : {}),\n };\n}\n\nfunction sameRequest(left: LayoutPathRequest, right: LayoutPathRequest): boolean {\n try {\n return (\n left.directory === right.directory &&\n left.name === right.name &&\n (left.extension ?? '') === (right.extension ?? '') &&\n (left.kind ?? (left.role === 'directory' ? 'directory' : 'file')) ===\n (right.kind ?? (right.role === 'directory' ? 'directory' : 'file')) &&\n left.role === right.role &&\n left.identity === right.identity &&\n JSON.stringify(normalizeRequiredLayoutChildren(left)) ===\n JSON.stringify(normalizeRequiredLayoutChildren(right))\n );\n } catch {\n return false;\n }\n}\n\nexport function inspectCurrentLayoutPlacement(input: CurrentLayoutPlacementInput): {\n placement: CurrentLayoutPlacement;\n diagnostics: ProjectionDiagnostic[];\n} {\n const diagnostics: ProjectionDiagnostic[] = [];\n const markers = new Map(\n input.scan.artifacts\n .filter((artifact) => artifact.role === 'folder-control' && artifact.present)\n .map((artifact) => [folderDirectory(artifact.path), artifact]),\n );\n const folderNames = (directory: string, file: string): Json[] | undefined => {\n const relative = directory === 'tree' ? '' : directory.slice('tree/'.length);\n if (!relative) return [];\n const parts = relative.split('/');\n const names: Json[] = [];\n for (let index = 0; index < parts.length; index++) {\n const physical = `tree/${parts.slice(0, index + 1).join('/')}`;\n const marker = markers.get(physical);\n if (!marker?.decodedName) {\n diagnostics.push(\n pathDiagnostic('incomplete-folder-chain', file, `Managed folder marker is missing for ${physical}`),\n );\n return undefined;\n }\n names.push(marker.decodedName);\n }\n return names;\n };\n\n const normalParents = new Map<string, string[]>([[canonicalFragmentHash([]), ['tree']]]);\n const normalMarkerNames = new Map<string, string[]>();\n for (const [directory, marker] of markers) {\n const names = folderNames(directory, marker.path);\n if (!names) continue;\n normalMarkerNames.set(directory, names as string[]);\n const key = canonicalFragmentHash(names);\n normalParents.set(key, [...(normalParents.get(key) ?? []), directory]);\n }\n const detachedParents = new Map<string, DetachedParentClaim[]>();\n for (const artifact of input.scan.artifacts) {\n if (artifact.role !== 'detached-document' || !artifact.present) continue;\n const value = object(artifact.json);\n const semantic = value?.kind === 'folder' ? detachedDocumentPlacement(value) : undefined;\n if (!value || !semantic) continue;\n const semanticPath = [...semantic.parent, semantic.name];\n const key = canonicalFragmentHash(semanticPath);\n const claim: DetachedParentClaim = {\n artifact,\n source: sourceFromValue(value),\n semanticPath,\n healthy: false,\n };\n detachedParents.set(key, [...(detachedParents.get(key) ?? []), claim]);\n }\n\n const resolveParent = (\n semantic: SemanticPlacement,\n ):\n | { type: 'normal'; directory: string }\n | { type: 'detached'; source: Extract<SourceIdentity, { type: 'resource' }>; semanticPathHash: string }\n | undefined => {\n const semanticPathHash = canonicalFragmentHash(semantic.parent);\n const normal = normalParents.get(semanticPathHash) ?? [];\n const detached = detachedParents.get(semanticPathHash) ?? [];\n if (normal.length + detached.length !== 1) return undefined;\n if (normal.length === 1) return { type: 'normal', directory: normal[0] };\n const parent = detached[0];\n return parent.healthy && parent.source\n ? { type: 'detached', source: parent.source, semanticPathHash }\n : undefined;\n };\n\n const validateRepresentationFallback = (\n proof: RepresentationFallbackProof,\n source: Extract<SourceIdentity, { type: 'resource' }>,\n semantic: SemanticPlacement,\n ): boolean => {\n if (proof.sourceKey !== sourceIdentityKey(source)) return false;\n const direct = proof.request !== undefined || proof.existingClaims !== undefined;\n const inherited = proof.inheritedFrom !== undefined;\n if (direct === inherited) return false;\n const parent = resolveParent(semantic);\n if (!parent) return false;\n const identity = 'id' in source.resource ? source.resource.id : source.resource.key;\n if (parent.type === 'detached')\n return (\n inherited &&\n proof.request === undefined &&\n proof.existingClaims === undefined &&\n proof.inheritedFrom.sourceKey === sourceIdentityKey(parent.source) &&\n proof.inheritedFrom.semanticPathHash === parent.semanticPathHash\n );\n if (!direct || inherited || !proof.request || !proof.existingClaims) return false;\n const expectedRequest = placementRequest(semantic, identity, parent.directory);\n return (\n sameRequest(proof.request, expectedRequest) &&\n provesUnrepresentableRequest(proof.request, proof.existingClaims)\n );\n };\n\n const validateDetachedDocument = (artifact: LayoutArtifact, value: JsonObject): boolean => {\n const source = sourceFromValue(value);\n const proof = input.detachedDocumentProofs[artifact.path];\n if (!source || !proof) return false;\n const identity = 'id' in source.resource ? source.resource.id : source.resource.key;\n let expected: string;\n try {\n expected = `detached/${source.resource.kind}/${encodeLayoutSegment(identity)}.json`;\n } catch {\n return false;\n }\n if (artifact.path !== expected || proof.sourceKey !== sourceIdentityKey(source)) return false;\n const placementHash = canonicalFragmentHash({\n name: value.name ?? null,\n folder: value.folder ?? null,\n path: value.path ?? null,\n parent: value.parent ?? null,\n });\n if (proof.reason === 'damage-proof') {\n if (!('id' in source.resource)) return false;\n const baseline = input.canonicalBaseline[`${source.resource.kind}/${source.resource.id}`];\n const definitionSlot = value.kind === 'dimension_table' ? 'table-definition' : 'document';\n const routes = input.groupedRoutes.filter((route) => sourceEquals(route.source, source));\n // The writer proves the placement it has just made; once the workspace routes the\n // resource, the proof has to name the file that route holds its definition in.\n const retained =\n routes.length === 0 ||\n routes.some((route) => route.selector.file === artifact.path && route.selector.slot === definitionSlot);\n const semantic = value.kind === 'folder' ? detachedDocumentPlacement(value) : undefined;\n const ownClaims = semantic\n ? (normalParents.get(canonicalFragmentHash([...semantic.parent, semantic.name]))?.length ?? 0) +\n (detachedParents.get(canonicalFragmentHash([...semantic.parent, semantic.name]))?.length ?? 0)\n : 0;\n return (\n proof.placementHash === placementHash &&\n proof.baselineHash === baseline &&\n retained &&\n (!semantic || ownClaims === 1)\n );\n }\n const semantic = detachedDocumentPlacement(value);\n if (!semantic || !validateRepresentationFallback(proof, source, semantic)) return false;\n if (value.kind !== 'folder') return true;\n const ownKey = canonicalFragmentHash([...semantic.parent, semantic.name]);\n return (normalParents.get(ownKey)?.length ?? 0) + (detachedParents.get(ownKey)?.length ?? 0) === 1;\n };\n\n const detachedValidation = new Map<string, boolean>();\n const folderClaims = [...detachedParents.values()]\n .flat()\n .sort(\n (left, right) =>\n left.semanticPath.length - right.semanticPath.length ||\n compareText(left.artifact.path, right.artifact.path),\n );\n for (const claim of folderClaims) {\n const value = object(claim.artifact.json)!;\n const valid = validateDetachedDocument(claim.artifact, value);\n detachedValidation.set(claim.artifact.path, valid);\n const proof = input.detachedDocumentProofs[claim.artifact.path];\n if (valid && proof?.reason === 'representation-fallback') claim.healthy = true;\n }\n\n const bind = (groupedSources: readonly WireSourceMapping[]): CurrentLayoutPlacement => {\n const sourceBoundFolders = new Map<string, CurrentFolderPlacement[]>();\n const collidingFolders = new Map<string, CurrentFolderPlacement[]>();\n const collisionKey = (semanticPath: readonly string[]) =>\n canonicalFragmentHash(semanticPath.map(layoutCollisionKey));\n const addSourceBoundFolder = (folder: CurrentFolderPlacement) => {\n const key = canonicalFragmentHash([...folder.semanticPath]);\n sourceBoundFolders.set(key, [...(sourceBoundFolders.get(key) ?? []), folder]);\n const folded = collisionKey(folder.semanticPath);\n collidingFolders.set(folded, [...(collidingFolders.get(folded) ?? []), folder]);\n };\n for (const [directory, marker] of markers) {\n const names = normalMarkerNames.get(directory);\n const value = object(marker.json);\n const authoredSource = value && sourceFromValue({ ...value, kind: 'folder' });\n if (!names) continue;\n const routes = groupedSources.filter(\n (mapping) =>\n mapping.selector.file === marker.path &&\n mapping.selector.slot === 'document' &&\n (authoredSource\n ? sourceEquals(mapping.source, authoredSource)\n : mapping.source.type === 'transient'),\n );\n if (routes.length === 1)\n addSourceBoundFolder({\n type: 'normal',\n source: routes[0].source,\n semanticPath: names as string[],\n directory,\n });\n }\n for (const claim of folderClaims) {\n const source = claim.source;\n const proof = input.detachedDocumentProofs[claim.artifact.path];\n if (!source || !proof || !detachedValidation.get(claim.artifact.path)) continue;\n const routes = groupedSources.filter(\n (mapping) =>\n sourceEquals(mapping.source, source) &&\n mapping.selector.file === claim.artifact.path &&\n mapping.selector.slot === 'document',\n );\n if (routes.length !== 1) continue;\n addSourceBoundFolder(\n proof.reason === 'representation-fallback'\n ? {\n type: 'detached-representation',\n source,\n semanticPath: claim.semanticPath,\n semanticPathHash: canonicalFragmentHash(claim.semanticPath),\n }\n : { type: 'damaged', source, semanticPath: claim.semanticPath },\n );\n }\n return {\n folderNames,\n folderPlacement: (semanticPath) => {\n const matches = sourceBoundFolders.get(canonicalFragmentHash([...semanticPath])) ?? [];\n return matches.length === 1 ? matches[0] : undefined;\n },\n collidingFolderPlacements: (semanticPath) => collidingFolders.get(collisionKey(semanticPath)) ?? [],\n detachedDocumentValid: (artifact, value) =>\n detachedValidation.get(artifact.path) ?? validateDetachedDocument(artifact, value),\n detachedFileValid: (artifact, value, folder) => {\n const proof = artifact.source ? input.detachedFileProofs[artifact.source] : undefined;\n if (proof?.reason !== 'representation-fallback') return true;\n const source = sourceFromValue({ ...value, kind: 'file' });\n const semantic = artifact.decodedName ? rawPlacement(artifact.decodedName, folder) : undefined;\n return !!source && !!semantic && validateRepresentationFallback(proof, source, semantic);\n },\n withGroupedSources: bind,\n };\n };\n return { placement: bind(input.groupedSources ?? []), diagnostics };\n}\nexport interface ProvenRawShareNavigationRoute {\n source: Extract<SourceIdentity, { type: 'resource' }>;\n selector: RawShareNavigation['selector'];\n sourcePath: ['shares'];\n groupFile: string;\n priorCleanHash: string;\n}\n\nexport interface RawShareNavigationObservation {\n source: Extract<SourceIdentity, { type: 'resource' }>;\n selector: RawShareNavigation['selector'];\n sourcePath: ['shares'];\n groupFile?: string;\n currentHash?: string;\n priorCleanHash?: string;\n state: 'clean' | 'dirty' | 'absent' | 'new';\n}\n\nexport interface LayoutSubmissionEvidence {\n groupedRoutes: readonly ProvenFragmentRoute[];\n binaryRoutes: readonly BinaryFragmentRoute[];\n groupedSubmissionProofs: readonly SubmissionCorrespondence[];\n binarySubmissionProofs: readonly BinarySubmissionProof[];\n derivedSourceProofs: readonly DerivedSourceProof[];\n rawNavigationRoutes: readonly ProvenRawShareNavigationRoute[];\n canonicalBaseline: Readonly<Record<string, string>>;\n detachedFileProofs: Readonly<Record<string, DetachedFileProof>>;\n detachedDocumentProofs: Readonly<Record<string, DetachedDocumentProof>>;\n /** The transient tokens of a saved submission, which a fresh fragment must never receive. */\n reservedTransientTokens?: readonly string[];\n}\n\nexport interface ComposeLayoutSubmissionInput {\n scan: LayoutScanResult;\n byteEvidence: LoadedLayoutByteEvidence;\n evidence: LayoutSubmissionEvidence;\n}\n\nexport interface LayoutCompositionContext {\n readonly scan: LayoutScanResult;\n readonly evidence: LayoutSubmissionEvidence;\n readonly groupedArtifacts: readonly GroupedLayoutArtifact[];\n readonly byteFacts: readonly LayoutByteFact[];\n /** Inspected once here and bound to this composition's grouped sources. Consumers must not re-inspect. */\n readonly placement: CurrentLayoutPlacement;\n}\n\nexport type LayoutSubmissionSource =\n | { codec: 'grouped'; mapping: WireSourceMapping }\n | { codec: 'raw'; mapping: RawFileWireSourceMapping };\n\n/**\n * The workspace file each submitted document came from, by its position in the submission: the\n * document's own file, a member set's table file, a share's group file or a raw file's sidecar.\n */\nexport function submittedDocumentFiles(sources: readonly LayoutSubmissionSource[]): Map<number, string> {\n const files = new Map<number, string>();\n for (const { codec, mapping } of sources) {\n // A navigation pointer is not where a document is authored.\n if (codec === 'grouped' && mapping.selector.slot === 'owner-navigation') continue;\n const file = codec === 'grouped' ? mapping.selector.file : mapping.selector.sidecar;\n if (!files.has(mapping.documentIndex)) files.set(mapping.documentIndex, file);\n }\n return files;\n}\n\nexport type ComposeLayoutSubmissionResult =\n | {\n status: 'complete';\n documents: Document[];\n sources: LayoutSubmissionSource[];\n grouped: ComposeGroupedLayoutResult;\n binary: ComposeBinaryLayoutResult;\n rawNavigation: RawShareNavigationObservation[];\n byteFacts: readonly LayoutByteFact[];\n /** Per-resource composition problems that never block a command; the caller reports them. */\n warnings: readonly ProjectionDiagnostic[];\n context: LayoutCompositionContext;\n }\n | {\n status: 'blocked';\n diagnostics: ProjectionDiagnostic[];\n byteFacts: readonly LayoutByteFact[];\n };\n\nfunction rawNavigationEvidenceDiagnostics(routes: readonly ProvenRawShareNavigationRoute[]): ProjectionDiagnostic[] {\n const diagnostics: ProjectionDiagnostic[] = [];\n const sources = new Set<string>();\n for (const route of routes) {\n const sourceKey = sourceIdentityKey(route.source);\n const identity = route.selector.identity;\n const sourceMatches =\n route.source.resource.kind === 'file' &&\n (('id' in route.source.resource && 'id' in identity && route.source.resource.id === identity.id) ||\n ('key' in route.source.resource && 'key' in identity && route.source.resource.key === identity.key));\n const valid =\n sourceMatches &&\n !sources.has(sourceKey) &&\n isRawSidecarPath(route.selector.sidecar) &&\n route.sourcePath.length === 1 &&\n route.sourcePath[0] === 'shares' &&\n /^access\\/shares\\/[^/]+\\.json$/.test(route.groupFile) &&\n route.priorCleanHash === canonicalFragmentHash(route.groupFile);\n if (!valid)\n diagnostics.push({\n code: 'invalid-raw-navigation-route',\n path: route.selector.sidecar,\n sourcePath: ['shares'],\n message: 'Raw share navigation evidence is not source-bound and internally consistent',\n });\n sources.add(sourceKey);\n }\n return diagnostics;\n}\n\ninterface PreparedArtifacts {\n grouped: GroupedLayoutArtifact[];\n raw: RawFileInput[];\n attachments: { artifact: GroupedLayoutArtifact; input: Omit<AttachmentInput, 'ownerSource'> }[];\n diagnostics: ProjectionDiagnostic[];\n placement: CurrentLayoutPlacement;\n}\n\nfunction prepareArtifacts(scan: LayoutScanResult, evidence: LayoutSubmissionEvidence): PreparedArtifacts {\n const inspected = inspectCurrentLayoutPlacement({\n scan,\n detachedDocumentProofs: evidence.detachedDocumentProofs,\n detachedFileProofs: evidence.detachedFileProofs,\n canonicalBaseline: evidence.canonicalBaseline,\n groupedRoutes: evidence.groupedRoutes,\n });\n const diagnostics = inspected.diagnostics;\n const placement = inspected.placement;\n const grouped: GroupedLayoutArtifact[] = [];\n const raw: RawFileInput[] = [];\n const attachments: PreparedArtifacts['attachments'] = [];\n for (const artifact of scan.artifacts) {\n if (\n (!artifact.present && artifact.role !== 'raw') ||\n artifact.role === 'raw-metadata' ||\n artifact.role === 'attachment'\n )\n continue;\n const value = object(artifact.json);\n if (!value) {\n diagnostics.push(pathDiagnostic('unclassified-layout-artifact', artifact.path, 'Artifact is not JSON'));\n continue;\n }\n if (artifact.role === 'raw') {\n const directory = parentDirectory(artifact.path);\n const detached = artifact.path.startsWith('detached/files/');\n const folder = detached ? value.folder : placement.folderNames(directory, artifact.path);\n if (!artifact.source || !artifact.decodedName || folder === undefined) {\n diagnostics.push(\n pathDiagnostic('incomplete-raw-artifact', artifact.path, 'Raw artifact lacks sidecar placement'),\n );\n continue;\n }\n const detachedProof = detached ? evidence.detachedFileProofs[artifact.source] : undefined;\n if (\n detachedProof?.reason === 'representation-fallback' &&\n !placement.detachedFileValid(artifact, value, folder)\n ) {\n diagnostics.push(\n pathDiagnostic(\n 'invalid-detached-proof',\n artifact.source,\n 'Detached raw placement lacks trusted parent proof',\n ),\n );\n continue;\n }\n raw.push({\n sidecar: artifact.source,\n bytes: artifact.path,\n metadata: value,\n name: artifact.decodedName,\n folder,\n ...(detachedProof ? { detached: detachedProof } : {}),\n });\n continue;\n }\n\n let semantic: JsonObject = { ...value };\n if (artifact.role === 'folder-control') {\n const names = placement.folderNames(folderDirectory(artifact.path), artifact.path);\n if (!names) continue;\n semantic = { ...semantic, kind: 'folder', path: names };\n delete semantic.name;\n } else if (artifact.role === 'document') {\n const folder = placement.folderNames(parentDirectory(artifact.path), artifact.path);\n if (!folder || !artifact.decodedName) continue;\n semantic = { ...semantic, name: artifact.decodedName, folder };\n } else if (FILENAME_NAME_ROLES.has(artifact.role)) {\n if (!artifact.decodedName) {\n diagnostics.push(\n pathDiagnostic('missing-layout-name', artifact.path, 'Artifact name cannot be decoded'),\n );\n continue;\n }\n semantic = { ...semantic, name: artifact.decodedName };\n } else if (artifact.role === 'detached-document' && !placement.detachedDocumentValid(artifact, semantic)) {\n diagnostics.push(\n pathDiagnostic(\n 'invalid-detached-proof',\n artifact.path,\n 'Detached document lacks trusted placement proof',\n ),\n );\n continue;\n }\n\n const role: GroupedLayoutArtifact['role'] =\n artifact.role === 'share-group'\n ? 'share-group'\n : semantic.kind === 'dimension_table'\n ? 'combined-table'\n : 'document';\n const groupedArtifact = { role, path: artifact.path, value: semantic } as GroupedLayoutArtifact;\n grouped.push(groupedArtifact);\n const field = ownerField(semantic);\n if (field)\n attachments.push({\n artifact: groupedArtifact,\n input: {\n origin: 'local',\n ownerFile: artifact.path,\n ownerDocument: semantic as Document,\n field,\n },\n });\n }\n\n return { grouped, raw, attachments, diagnostics, placement };\n}\n\nfunction binaryBaselines(raw: readonly RawFileInput[], baseline: Readonly<Record<string, string>>) {\n return raw.flatMap((candidate): AuthoritativeBinaryBaseline[] => {\n const id = candidate.metadata.id;\n return typeof id === 'string' && baseline[`file/${id}`]\n ? [\n {\n source: { type: 'resource', resource: { kind: 'file', id } },\n canonicalHash: baseline[`file/${id}`],\n },\n ]\n : [];\n });\n}\n\nfunction blocked(\n diagnostics: readonly ProjectionDiagnostic[],\n byteFacts: readonly LayoutByteFact[],\n): ComposeLayoutSubmissionResult {\n return { status: 'blocked', diagnostics: [...diagnostics], byteFacts };\n}\n\nexport function composeLayoutSubmission(input: ComposeLayoutSubmissionInput): ComposeLayoutSubmissionResult {\n const initialDiagnostics: ProjectionDiagnostic[] = [\n ...input.scan.diagnostics.map((diagnostic) => ({ ...diagnostic })),\n ...input.byteEvidence.diagnostics,\n ];\n if (initialDiagnostics.length > 0) return blocked(initialDiagnostics, input.byteEvidence.facts);\n const warnings: ProjectionDiagnostic[] = [];\n // A `name` field that spells another name than the filename is no rename; say which one counts.\n for (const artifact of input.scan.artifacts)\n if (artifact.ignoredNameOverride !== undefined && artifact.decodedName !== undefined)\n warnings.push(\n pathDiagnostic(\n 'name-override-ignored',\n artifact.source ?? artifact.path,\n `the \"name\" field says ${JSON.stringify(artifact.ignoredNameOverride)} but the filename names ` +\n `${JSON.stringify(artifact.decodedName)}; the filename is the name, so rename the file to rename the resource`,\n ),\n );\n /** A lost transient correspondence already minted a fresh token, so it warns instead of blocking. */\n const blocking = (diagnostics: readonly ProjectionDiagnostic[]): ProjectionDiagnostic[] => {\n const rest: ProjectionDiagnostic[] = [];\n for (const item of diagnostics) (item.code === 'lost-source-correspondence' ? warnings : rest).push(item);\n return rest;\n };\n\n const prepared = prepareArtifacts(input.scan, input.evidence);\n if (prepared.diagnostics.length > 0) return blocked(prepared.diagnostics, input.byteEvidence.facts);\n const navigationDiagnostics = rawNavigationEvidenceDiagnostics(input.evidence.rawNavigationRoutes);\n if (navigationDiagnostics.length > 0) return blocked(navigationDiagnostics, input.byteEvidence.facts);\n\n const retainedBinaryRoutes = input.evidence.binaryRoutes.filter(\n (route) => !(route.source.type === 'transient' && route.selector.slot === 'owner-attachment'),\n );\n const preflightAttachments: AttachmentInput[] = prepared.attachments.map(({ input: attachment }, index) => {\n const value = object(attachment.ownerDocument)!;\n return {\n ...attachment,\n ownerSource:\n sourceFromValue(value) ?? ({ type: 'transient', token: `layout-preflight:${index + 1}` } as const),\n };\n });\n const preflight = composeBinaryLayout({\n rawFiles: prepared.raw,\n attachments: preflightAttachments,\n bytes: input.byteEvidence.facts,\n priorRoutes: retainedBinaryRoutes,\n submissionProofs: input.evidence.binarySubmissionProofs,\n reservedTransientTokens: input.evidence.reservedTransientTokens,\n authoritativeBaselines: binaryBaselines(prepared.raw, input.evidence.canonicalBaseline),\n });\n const preflightBlocking = blocking(preflight.diagnostics);\n if (preflightBlocking.length > 0) return blocked(preflightBlocking, input.byteEvidence.facts);\n const unkeyedNavigation = preflight.navigation.find((navigation) => navigation.source.type === 'transient');\n if (unkeyedNavigation)\n return blocked(\n [\n {\n code: 'unkeyed-raw-share-owner',\n path: unkeyedNavigation.selector.sidecar,\n sourcePath: [...unkeyedNavigation.sourcePath],\n message: 'A raw share pointer requires an ID or committed key',\n },\n ],\n input.byteEvidence.facts,\n );\n\n const normalizedArtifacts = prepared.grouped.map((artifact) => {\n const projected = preflight.ownerFields.filter((field) => field.ownerFile === artifact.path);\n if (projected.length === 0 || artifact.role === 'share-group') return artifact;\n const value: JsonObject = { ...artifact.value };\n for (const field of projected) {\n if (field.status === 'value') value[field.field] = field.value as Json;\n else if (field.status === 'omitted') delete value[field.field];\n }\n return { ...artifact, value } as GroupedLayoutArtifact;\n });\n\n const navigationBySource = new Map(\n preflight.navigation.map((navigation) => [sourceIdentityKey(navigation.source), navigation]),\n );\n const priorNavigationBySource = new Map(\n input.evidence.rawNavigationRoutes.map((navigation) => [sourceIdentityKey(navigation.source), navigation]),\n );\n const externalOwners: ExternalGroupedOwner[] = preflight.rawSources.flatMap((mapping) => {\n if (mapping.source.type !== 'resource') return [];\n const document = preflight.rawDocuments[mapping.documentIndex];\n const owner =\n 'id' in mapping.source.resource\n ? ({ kind: 'file', id: mapping.source.resource.id } as const)\n : ({ kind: 'file', key: mapping.source.resource.key } as const);\n const currentNavigation = navigationBySource.get(sourceIdentityKey(mapping.source));\n const priorNavigation = priorNavigationBySource.get(sourceIdentityKey(mapping.source));\n return [\n {\n source: mapping.source,\n owner,\n value: document,\n location: { file: mapping.selector.sidecar, path: [] },\n ...(currentNavigation ? { currentGroupFile: currentNavigation.groupFile } : {}),\n ...(priorNavigation ? { priorGroupFile: priorNavigation.groupFile } : {}),\n },\n ];\n });\n\n const grouped = composeGroupedLayout({\n artifacts: normalizedArtifacts,\n externalOwners,\n priorRoutes: input.evidence.groupedRoutes,\n submissionProofs: input.evidence.groupedSubmissionProofs,\n reservedTransientTokens: input.evidence.reservedTransientTokens,\n derivedSourceProofs: input.evidence.derivedSourceProofs,\n });\n const groupedBlocking = blocking(grouped.diagnostics);\n if (groupedBlocking.length > 0) return blocked(groupedBlocking, input.byteEvidence.facts);\n grouped.diagnostics = groupedBlocking;\n\n const finalAttachments: AttachmentInput[] = prepared.attachments.flatMap(({ input: attachment }) => {\n const mapping = grouped.sources.find(\n (source) => source.selector.file === attachment.ownerFile && source.selector.slot === 'document',\n );\n return mapping ? [{ ...attachment, ownerSource: mapping.source }] : [];\n });\n if (finalAttachments.length !== prepared.attachments.length)\n return blocked(\n [pathDiagnostic('missing-owner-source', '.', 'Attachment owner has no grouped source mapping')],\n input.byteEvidence.facts,\n );\n const binary = composeBinaryLayout({\n rawFiles: prepared.raw,\n attachments: finalAttachments,\n bytes: input.byteEvidence.facts,\n priorRoutes: retainedBinaryRoutes,\n submissionProofs: input.evidence.binarySubmissionProofs,\n reservedTransientTokens: input.evidence.reservedTransientTokens,\n authoritativeBaselines: binaryBaselines(prepared.raw, input.evidence.canonicalBaseline),\n });\n const binaryBlocking = blocking(binary.diagnostics);\n if (binaryBlocking.length > 0) return blocked(binaryBlocking, input.byteEvidence.facts);\n binary.diagnostics = binaryBlocking;\n\n const rawNavigation: RawShareNavigationObservation[] = [];\n const matchedPrior = new Set<string>();\n for (const current of binary.navigation) {\n if (current.source.type !== 'resource') continue;\n const key = sourceIdentityKey(current.source);\n const prior = priorNavigationBySource.get(key);\n if (prior) matchedPrior.add(key);\n rawNavigation.push({\n source: current.source,\n selector: current.selector,\n sourcePath: current.sourcePath,\n groupFile: current.groupFile,\n currentHash: current.currentHash,\n ...(prior ? { priorCleanHash: prior.priorCleanHash } : {}),\n state: prior ? (prior.priorCleanHash === current.currentHash ? 'clean' : 'dirty') : 'new',\n });\n }\n for (const prior of input.evidence.rawNavigationRoutes)\n if (!matchedPrior.has(sourceIdentityKey(prior.source)))\n rawNavigation.push({\n source: prior.source,\n selector: prior.selector,\n sourcePath: prior.sourcePath,\n priorCleanHash: prior.priorCleanHash,\n state: 'absent',\n });\n\n const documents = [...grouped.documents, ...binary.rawDocuments];\n const sources: LayoutSubmissionSource[] = [\n ...grouped.sources.map((mapping) => ({ codec: 'grouped' as const, mapping })),\n ...binary.rawSources.map((mapping) => ({\n codec: 'raw' as const,\n mapping: { ...mapping, documentIndex: mapping.documentIndex + grouped.documents.length },\n })),\n ];\n const composed = clone({\n status: 'complete' as const,\n documents,\n sources,\n grouped,\n binary,\n rawNavigation,\n byteFacts: input.byteEvidence.facts,\n warnings,\n context: {\n scan: input.scan,\n evidence: input.evidence,\n groupedArtifacts: normalizedArtifacts,\n byteFacts: input.byteEvidence.facts,\n },\n });\n // The placement holds closures, so it joins the context after the value clone.\n return {\n ...composed,\n context: { ...composed.context, placement: prepared.placement.withGroupedSources(grouped.sources) },\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,oCAYO;AACP,wBAWO;AACP,yBAUO;AACP,8BAWO;AAmFP,SAAS,aAAa,MAAsB,OAAgC;AACxE,aAAO,qCAAkB,IAAI,UAAM,qCAAkB,KAAK;AAC9D;AAEA,SAAS,uBAAuB,WAAuC;AACnE,MAAI,CAAC,UAAU,QAAQ,UAAU,OAAO,KAAK,CAAC,SAAS,CAAC,IAAI,EAAG,QAAO;AACtE,MAAI;AACA,gDAAoB,UAAU,IAAI;AAClC,eAAW,QAAQ,UAAU,OAAQ,6CAAoB,IAAI;AAC7D,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,SAAS,0BAA0B,OAAkD;AACjF,MAAI,MAAM,SAAS,UAAU;AACzB,QACI,CAAC,MAAM,QAAQ,MAAM,IAAI,KACzB,MAAM,KAAK,WAAW,KACtB,MAAM,KAAK,KAAK,CAAC,SAAS,OAAO,SAAS,YAAY,KAAK,WAAW,CAAC;AAEvE,aAAO;AACX,UAAM,QAAQ,MAAM;AACpB,UAAMA,aAA+B;AAAA,MACjC,QAAQ,MAAM,MAAM,GAAG,EAAE;AAAA,MACzB,MAAM,MAAM,GAAG,EAAE;AAAA,MACjB,MAAM;AAAA,IACV;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AAA,QAChB,YAAY,MAAM;AAAA,QAClB,gBAAgB,MAAM;AAAA,QACtB,OAAO;AAAA,MACX,CAAC;AAET,QAAM,YAAY,CAAC,GAAG,QAAQ,WAAW,GAAG,OAAO,YAAY;AAC/D,QAAM,UAAoC;AAAA,IACtC,GAAG,QAAQ,QAAQ,IAAI,CAAC,aAAa,EAAE,OAAO,WAAoB,QAAQ,EAAE;AAAA,IAC5E,GAAG,OAAO,WAAW,IAAI,CAAC,aAAa;AAAA,MACnC,OAAO;AAAA,MACP,SAAS,EAAE,GAAG,SAAS,eAAe,QAAQ,gBAAgB,QAAQ,UAAU,OAAO;AAAA,IAC3F,EAAE;AAAA,EACN;AACA,QAAM,eAAW,yBAAM;AAAA,IACnB,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,MAAM,aAAa;AAAA,IAC9B;AAAA,IACA,SAAS;AAAA,MACL,MAAM,MAAM;AAAA,MACZ,UAAU,MAAM;AAAA,MAChB,kBAAkB;AAAA,MAClB,WAAW,MAAM,aAAa;AAAA,IAClC;AAAA,EACJ,CAAC;AAED,SAAO;AAAA,IACH,GAAG;AAAA,IACH,SAAS,EAAE,GAAG,SAAS,SAAS,WAAW,SAAS,UAAU,mBAAmB,QAAQ,OAAO,EAAE;AAAA,EACtG;AACJ;",
6
+ "names": ["placement", "pathDiagnostic", "semantic", "ownerField"]
7
+ }
@@ -0,0 +1,260 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var layoutCore_exports = {};
20
+ __export(layoutCore_exports, {
21
+ FILENAME_NAME_ROLES: () => FILENAME_NAME_ROLES,
22
+ ITEM_KINDS: () => ITEM_KINDS,
23
+ RESOURCE_ID: () => RESOURCE_ID,
24
+ SHA256: () => SHA256,
25
+ TREE_DOCUMENT_KINDS: () => TREE_DOCUMENT_KINDS,
26
+ allocateSubmissionToken: () => allocateSubmissionToken,
27
+ attachmentField: () => attachmentField,
28
+ attachmentPointer: () => attachmentPointer,
29
+ blocked: () => blocked,
30
+ canonicalFragmentHash: () => canonicalFragmentHash,
31
+ clone: () => clone,
32
+ cloneOptional: () => cloneOptional,
33
+ compareText: () => compareText,
34
+ diagnostic: () => diagnostic,
35
+ groupBySource: () => groupBySource,
36
+ hashCanonicalText: () => hashCanonicalText,
37
+ indexBySource: () => indexBySource,
38
+ isObject: () => isObject,
39
+ matchExactSubmissionProof: () => matchExactSubmissionProof,
40
+ object: () => object,
41
+ own: () => own,
42
+ ownerKey: () => ownerKey,
43
+ pathAncestors: () => pathAncestors,
44
+ same: () => same,
45
+ samePath: () => samePath,
46
+ sameSelector: () => sameSelector,
47
+ sourceFromValue: () => sourceFromValue,
48
+ sourceIdentityKey: () => sourceIdentityKey,
49
+ stableSource: () => stableSource,
50
+ validBlob: () => validBlob,
51
+ without: () => without
52
+ });
53
+ module.exports = __toCommonJS(layoutCore_exports);
54
+ var import_crypto = require("crypto");
55
+ var import_documents = require("./documents");
56
+ const RESOURCE_ID = /^(0|[1-9][0-9]*)$/;
57
+ const SHA256 = /^[a-f0-9]{64}$/;
58
+ const TREE_DOCUMENT_KINDS = /* @__PURE__ */ new Set(["variable", "dimension_table", "sheet", "dashboard", "remote_job"]);
59
+ const ITEM_KINDS = /* @__PURE__ */ new Set(["folder", ...TREE_DOCUMENT_KINDS]);
60
+ const FILENAME_NAME_ROLES = /* @__PURE__ */ new Set(["user-group", "label", "dataset", "export"]);
61
+ function clone(value) {
62
+ return cloneJson(value);
63
+ }
64
+ function omittedByJson(value) {
65
+ return value === void 0 || typeof value === "function" || typeof value === "symbol";
66
+ }
67
+ function cloneJson(value) {
68
+ switch (typeof value) {
69
+ case "string":
70
+ case "boolean":
71
+ return value;
72
+ case "number":
73
+ return Number.isFinite(value) ? value === 0 ? 0 : value : null;
74
+ case "object": {
75
+ if (value === null) return null;
76
+ if (Array.isArray(value)) {
77
+ const copy2 = new Array(value.length);
78
+ for (let index = 0; index < value.length; index++) {
79
+ const item = value[index];
80
+ copy2[index] = omittedByJson(item) ? null : cloneJson(item);
81
+ }
82
+ return copy2;
83
+ }
84
+ const prototype = Object.getPrototypeOf(value);
85
+ const record = value;
86
+ if (prototype !== Object.prototype && prototype !== null || typeof record.toJSON === "function") break;
87
+ const copy = {};
88
+ for (const key of Object.keys(record)) {
89
+ const item = record[key];
90
+ if (omittedByJson(item)) continue;
91
+ if (key === "__proto__")
92
+ Object.defineProperty(copy, key, {
93
+ value: cloneJson(item),
94
+ enumerable: true,
95
+ writable: true,
96
+ configurable: true
97
+ });
98
+ else copy[key] = cloneJson(item);
99
+ }
100
+ return copy;
101
+ }
102
+ }
103
+ return JSON.parse(JSON.stringify(value));
104
+ }
105
+ function cloneOptional(value) {
106
+ if (value === void 0) return value;
107
+ return clone(value);
108
+ }
109
+ function object(value) {
110
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
111
+ }
112
+ function isObject(value) {
113
+ return value !== null && typeof value === "object" && !Array.isArray(value);
114
+ }
115
+ function own(value, field) {
116
+ return Object.prototype.hasOwnProperty.call(value, field);
117
+ }
118
+ function without(value, fields) {
119
+ return Object.fromEntries(Object.entries(value).filter(([field]) => !fields.includes(field)));
120
+ }
121
+ function compareText(left, right) {
122
+ return left < right ? -1 : left > right ? 1 : 0;
123
+ }
124
+ function same(left, right) {
125
+ return (0, import_documents.canonicalEqual)(left, right);
126
+ }
127
+ function samePath(left, right) {
128
+ return JSON.stringify(left) === JSON.stringify(right);
129
+ }
130
+ function sameSelector(left, right) {
131
+ if (left.file !== right.file || left.slot !== right.slot) return false;
132
+ if (left.slot !== "share-entry" || right.slot !== "share-entry") return true;
133
+ return (0, import_documents.canonicalText)(left.identity) === (0, import_documents.canonicalText)(right.identity);
134
+ }
135
+ function diagnostic(code, path, message, sourcePath) {
136
+ return { code, path, message, ...sourcePath ? { sourcePath } : {} };
137
+ }
138
+ function blocked(diagnostics) {
139
+ return { status: "blocked", diagnostics: [...diagnostics] };
140
+ }
141
+ function validBlob(value) {
142
+ const candidate = object(value);
143
+ return !!candidate && typeof candidate.sha256 === "string" && SHA256.test(candidate.sha256) && Number.isSafeInteger(candidate.size) && Number(candidate.size) >= 0;
144
+ }
145
+ function attachmentField(value) {
146
+ if (value.kind === "remote_job") return "icon";
147
+ if (value.kind === "export_configuration") return "template";
148
+ return void 0;
149
+ }
150
+ function attachmentPointer(value) {
151
+ if (value === null || value === void 0) return value;
152
+ const pointer = object(value);
153
+ return pointer && Object.keys(pointer).length === 1 && typeof pointer.file === "string" ? pointer.file : void 0;
154
+ }
155
+ function sourceFromValue(value) {
156
+ if (typeof value.kind !== "string") return void 0;
157
+ if (typeof value.id === "string" && RESOURCE_ID.test(value.id))
158
+ return { type: "resource", resource: { kind: value.kind, id: value.id } };
159
+ if (typeof value.key === "string" && value.key.length > 0)
160
+ return { type: "resource", resource: { kind: value.kind, key: value.key } };
161
+ return void 0;
162
+ }
163
+ function ownerKey(owner) {
164
+ if ("id" in owner) return `${owner.kind}/id/${owner.id}`;
165
+ if ("key" in owner) return `${owner.kind}/key/${owner.key}`;
166
+ return `${owner.kind}/dangling/${owner.dangling}`;
167
+ }
168
+ function stableSource(key) {
169
+ const slash = key.indexOf("/");
170
+ const kind = key.slice(0, slash);
171
+ const id = key.slice(slash + 1);
172
+ return slash > 0 && kind.length > 0 && RESOURCE_ID.test(id) ? { type: "resource", resource: { kind, id } } : void 0;
173
+ }
174
+ function pathAncestors(relative) {
175
+ const parts = relative.split("/");
176
+ return Array.from({ length: parts.length - 1 }, (_, index) => parts.slice(0, index + 1).join("/"));
177
+ }
178
+ function sourceIdentityKey(source) {
179
+ if (source.type === "transient") return `transient/${source.token}`;
180
+ if (source.type === "group") return `group/${ownerKey(source.owner)}`;
181
+ return "id" in source.resource ? `resource/${source.resource.kind}/id/${source.resource.id}` : `resource/${source.resource.kind}/key/${source.resource.key}`;
182
+ }
183
+ function groupBySource(items, key) {
184
+ const index = /* @__PURE__ */ new Map();
185
+ for (const item of items) {
186
+ const identity = key(item);
187
+ index.set(identity, [...index.get(identity) ?? [], item]);
188
+ }
189
+ return index;
190
+ }
191
+ function indexBySource(items, key, label) {
192
+ const index = /* @__PURE__ */ new Map();
193
+ for (const item of items) {
194
+ const identity = key(item);
195
+ if (index.has(identity)) throw new Error(`${label} has more than one entry for ${identity}`);
196
+ index.set(identity, item);
197
+ }
198
+ return index;
199
+ }
200
+ function canonicalFragmentHash(value) {
201
+ return hashCanonicalText((0, import_documents.canonicalText)(value));
202
+ }
203
+ function hashCanonicalText(text) {
204
+ return (0, import_crypto.createHash)("sha256").update(text).digest("hex");
205
+ }
206
+ function matchExactSubmissionProof(proofs, candidates) {
207
+ const scoped = proofs.filter((proof) => candidates.some((candidate) => candidate.scopeKey === proof.scopeKey));
208
+ const exact = scoped.flatMap(
209
+ (proof) => candidates.filter(
210
+ (candidate) => candidate.scopeKey === proof.scopeKey && JSON.stringify(candidate.sourcePath) === JSON.stringify(proof.sourcePath) && proof.evidenceHash !== void 0 && proof.evidenceHash.length > 0 && candidate.evidenceHash === proof.evidenceHash
211
+ ).map(() => proof)
212
+ );
213
+ const tokens = [...new Set(exact.map((proof) => proof.token))];
214
+ if (tokens.length === 1) return { status: "matched", token: tokens[0], exactMatchCount: exact.length };
215
+ if (tokens.length > 1) return { status: "ambiguous", exactMatchCount: exact.length };
216
+ return { status: scoped.length > 0 ? "lost" : "missing", exactMatchCount: 0 };
217
+ }
218
+ function allocateSubmissionToken(usedTokens, sequence, namespace = "submission") {
219
+ let token;
220
+ do
221
+ token = `${namespace}:${++sequence}`;
222
+ while (usedTokens.has(token));
223
+ usedTokens.add(token);
224
+ return { token, sequence };
225
+ }
226
+ // Annotate the CommonJS export names for ESM import in node:
227
+ 0 && (module.exports = {
228
+ FILENAME_NAME_ROLES,
229
+ ITEM_KINDS,
230
+ RESOURCE_ID,
231
+ SHA256,
232
+ TREE_DOCUMENT_KINDS,
233
+ allocateSubmissionToken,
234
+ attachmentField,
235
+ attachmentPointer,
236
+ blocked,
237
+ canonicalFragmentHash,
238
+ clone,
239
+ cloneOptional,
240
+ compareText,
241
+ diagnostic,
242
+ groupBySource,
243
+ hashCanonicalText,
244
+ indexBySource,
245
+ isObject,
246
+ matchExactSubmissionProof,
247
+ object,
248
+ own,
249
+ ownerKey,
250
+ pathAncestors,
251
+ same,
252
+ samePath,
253
+ sameSelector,
254
+ sourceFromValue,
255
+ sourceIdentityKey,
256
+ stableSource,
257
+ validBlob,
258
+ without
259
+ });
260
+ //# sourceMappingURL=layoutCore.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/codefirst/layoutCore.ts"],
4
+ "sourcesContent": ["/**\n * Shared primitives for the layout modules: JSON shape helpers, canonical comparisons,\n * diagnostic constructors, identity keys and the submission proof matcher.\n * Every helper here is imported by two or more layout modules.\n */\nimport { createHash } from 'crypto';\nimport { canonicalEqual, canonicalText } from './documents';\nimport type { FragmentSelector, GroupOwnerSelector, ProjectionDiagnostic, SourceIdentity } from './layoutProjection';\nimport type { BlobContent, Json } from './types';\n\nexport type JsonObject = { [key: string]: Json };\nexport type StableSource = Extract<SourceIdentity, { type: 'resource' }> & {\n resource: { kind: string; id: string };\n};\n\nexport const RESOURCE_ID = /^(0|[1-9][0-9]*)$/;\nexport const SHA256 = /^[a-f0-9]{64}$/;\nexport const TREE_DOCUMENT_KINDS = new Set(['variable', 'dimension_table', 'sheet', 'dashboard', 'remote_job']);\nexport const ITEM_KINDS = new Set(['folder', ...TREE_DOCUMENT_KINDS]);\nexport const FILENAME_NAME_ROLES = new Set<string>(['user-group', 'label', 'dataset', 'export']);\n\n/**\n * A deep copy with the result of a JSON round trip: undefined, function and symbol members are\n * dropped (null inside arrays), non-finite numbers become null and -0 becomes 0. Plain objects and\n * arrays are copied directly; anything else goes through the round trip itself.\n */\nexport function clone<T>(value: T): T {\n return cloneJson(value) as T;\n}\n\nfunction omittedByJson(value: unknown): boolean {\n return value === undefined || typeof value === 'function' || typeof value === 'symbol';\n}\n\nfunction cloneJson(value: unknown): unknown {\n switch (typeof value) {\n case 'string':\n case 'boolean':\n return value;\n case 'number':\n return Number.isFinite(value) ? (value === 0 ? 0 : value) : null;\n case 'object': {\n if (value === null) return null;\n if (Array.isArray(value)) {\n const copy = new Array<unknown>(value.length);\n for (let index = 0; index < value.length; index++) {\n const item: unknown = value[index];\n copy[index] = omittedByJson(item) ? null : cloneJson(item);\n }\n return copy;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n const record = value as Record<string, unknown>;\n if ((prototype !== Object.prototype && prototype !== null) || typeof record.toJSON === 'function') break;\n const copy: Record<string, unknown> = {};\n for (const key of Object.keys(record)) {\n const item = record[key];\n if (omittedByJson(item)) continue;\n // An own `__proto__` key stays a key, as JSON.parse creates it.\n if (key === '__proto__')\n Object.defineProperty(copy, key, {\n value: cloneJson(item),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n else copy[key] = cloneJson(item);\n }\n return copy;\n }\n }\n return JSON.parse(JSON.stringify(value)) as unknown;\n}\n\n/** Like {@link clone}, but passes `undefined` through instead of failing to parse it. */\nexport function cloneOptional<T>(value: T): T {\n if (value === undefined) return value;\n return clone(value);\n}\n\nexport function object(value: unknown): JsonObject | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as JsonObject) : undefined;\n}\n\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function own(value: object, field: string): boolean {\n return Object.prototype.hasOwnProperty.call(value, field);\n}\n\nexport function without(value: JsonObject, fields: readonly string[]): JsonObject {\n return Object.fromEntries(Object.entries(value).filter(([field]) => !fields.includes(field)));\n}\n\nexport function compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nexport function same(left: unknown, right: unknown): boolean {\n return canonicalEqual(left as Json, right as Json);\n}\n\nexport function samePath(left: readonly (string | number)[], right: readonly (string | number)[]): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport function sameSelector(left: FragmentSelector, right: FragmentSelector): boolean {\n if (left.file !== right.file || left.slot !== right.slot) return false;\n if (left.slot !== 'share-entry' || right.slot !== 'share-entry') return true;\n return canonicalText(left.identity) === canonicalText(right.identity);\n}\n\nexport function diagnostic(\n code: string,\n path: string,\n message: string,\n sourcePath?: (string | number)[],\n): ProjectionDiagnostic {\n return { code, path, message, ...(sourcePath ? { sourcePath } : {}) };\n}\n\nexport function blocked(diagnostics: readonly ProjectionDiagnostic[]): {\n status: 'blocked';\n diagnostics: ProjectionDiagnostic[];\n} {\n return { status: 'blocked', diagnostics: [...diagnostics] };\n}\n\nexport function validBlob(value: unknown): value is BlobContent {\n const candidate = object(value);\n return (\n !!candidate &&\n typeof candidate.sha256 === 'string' &&\n SHA256.test(candidate.sha256) &&\n Number.isSafeInteger(candidate.size) &&\n Number(candidate.size) >= 0\n );\n}\n\nexport function attachmentField(value: { kind?: unknown }): 'icon' | 'template' | undefined {\n if (value.kind === 'remote_job') return 'icon';\n if (value.kind === 'export_configuration') return 'template';\n return undefined;\n}\n\nexport function attachmentPointer(value: Json | undefined): string | null | undefined {\n if (value === null || value === undefined) return value;\n const pointer = object(value);\n return pointer && Object.keys(pointer).length === 1 && typeof pointer.file === 'string' ? pointer.file : undefined;\n}\n\nexport function sourceFromValue(value: JsonObject): Extract<SourceIdentity, { type: 'resource' }> | undefined {\n if (typeof value.kind !== 'string') return undefined;\n if (typeof value.id === 'string' && RESOURCE_ID.test(value.id))\n return { type: 'resource', resource: { kind: value.kind, id: value.id } };\n if (typeof value.key === 'string' && value.key.length > 0)\n return { type: 'resource', resource: { kind: value.kind, key: value.key } };\n return undefined;\n}\n\nexport function ownerKey(owner: GroupOwnerSelector): string {\n if ('id' in owner) return `${owner.kind}/id/${owner.id}`;\n if ('key' in owner) return `${owner.kind}/key/${owner.key}`;\n return `${owner.kind}/dangling/${owner.dangling}`;\n}\n\nexport function stableSource(key: string): StableSource | undefined {\n const slash = key.indexOf('/');\n const kind = key.slice(0, slash);\n const id = key.slice(slash + 1);\n return slash > 0 && kind.length > 0 && RESOURCE_ID.test(id)\n ? { type: 'resource', resource: { kind, id } }\n : undefined;\n}\n\nexport function pathAncestors(relative: string): string[] {\n const parts = relative.split('/');\n return Array.from({ length: parts.length - 1 }, (_, index) => parts.slice(0, index + 1).join('/'));\n}\n\nexport interface SubmissionProofEvidence {\n token: string;\n scopeKey: string;\n sourcePath: readonly (string | number)[];\n evidenceHash?: string;\n}\n\nexport interface SubmissionCandidateEvidence {\n scopeKey: string;\n sourcePath: readonly (string | number)[];\n evidenceHash: string;\n}\n\nexport type SubmissionProofMatch =\n | { status: 'matched'; token: string; exactMatchCount: number }\n | { status: 'missing' | 'lost' | 'ambiguous'; exactMatchCount: number };\n\nexport function sourceIdentityKey(source: SourceIdentity): string {\n if (source.type === 'transient') return `transient/${source.token}`;\n if (source.type === 'group') return `group/${ownerKey(source.owner)}`;\n return 'id' in source.resource\n ? `resource/${source.resource.kind}/id/${source.resource.id}`\n : `resource/${source.resource.kind}/key/${source.resource.key}`;\n}\n\n/** Group composition products by source identity. Products repeat per selector, so each key holds a list. */\nexport function groupBySource<T>(items: readonly T[], key: (item: T) => string): Map<string, T[]> {\n const index = new Map<string, T[]>();\n for (const item of items) {\n const identity = key(item);\n index.set(identity, [...(index.get(identity) ?? []), item]);\n }\n return index;\n}\n\n/**\n * Index composition products that carry one entry per source identity. The codecs block duplicate\n * identities, so a second entry for one key is an impossible state rather than a user diagnostic.\n */\nexport function indexBySource<T>(items: readonly T[], key: (item: T) => string, label: string): Map<string, T> {\n const index = new Map<string, T>();\n for (const item of items) {\n const identity = key(item);\n if (index.has(identity)) throw new Error(`${label} has more than one entry for ${identity}`);\n index.set(identity, item);\n }\n return index;\n}\n\nexport function canonicalFragmentHash(value: Json): string {\n return hashCanonicalText(canonicalText(value));\n}\n\n/** The fragment hash of a value whose canonical text the caller already holds. */\nexport function hashCanonicalText(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n\nexport function matchExactSubmissionProof(\n proofs: readonly SubmissionProofEvidence[],\n candidates: readonly SubmissionCandidateEvidence[],\n): SubmissionProofMatch {\n const scoped = proofs.filter((proof) => candidates.some((candidate) => candidate.scopeKey === proof.scopeKey));\n const exact = scoped.flatMap((proof) =>\n candidates\n .filter(\n (candidate) =>\n candidate.scopeKey === proof.scopeKey &&\n JSON.stringify(candidate.sourcePath) === JSON.stringify(proof.sourcePath) &&\n proof.evidenceHash !== undefined &&\n proof.evidenceHash.length > 0 &&\n candidate.evidenceHash === proof.evidenceHash,\n )\n .map(() => proof),\n );\n const tokens = [...new Set(exact.map((proof) => proof.token))];\n if (tokens.length === 1) return { status: 'matched', token: tokens[0], exactMatchCount: exact.length };\n if (tokens.length > 1) return { status: 'ambiguous', exactMatchCount: exact.length };\n return { status: scoped.length > 0 ? 'lost' : 'missing', exactMatchCount: 0 };\n}\n\nexport function allocateSubmissionToken(\n usedTokens: Set<string>,\n sequence: number,\n namespace = 'submission',\n): { token: string; sequence: number } {\n let token: string;\n do token = `${namespace}:${++sequence}`;\n while (usedTokens.has(token));\n usedTokens.add(token);\n return { token, sequence };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;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