@_linked/core 2.31.0 → 2.33.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 (43) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +61 -61
  3. package/lib/esm/index.d.ts +1 -0
  4. package/lib/esm/index.js.map +1 -1
  5. package/lib/esm/ontologies/linked-core.d.ts +1 -0
  6. package/lib/esm/ontologies/linked-core.js +8 -2
  7. package/lib/esm/ontologies/linked-core.js.map +1 -1
  8. package/lib/esm/ontologies/shacl.d.ts +3 -0
  9. package/lib/esm/ontologies/shacl.js +6 -0
  10. package/lib/esm/ontologies/shacl.js.map +1 -1
  11. package/lib/esm/shapes/List.class.d.ts +3 -3
  12. package/lib/esm/shapes/List.class.js +3 -3
  13. package/lib/esm/shapes/List.class.js.map +1 -1
  14. package/lib/esm/shapes/PathList.d.ts +5 -8
  15. package/lib/esm/shapes/PathList.js +6 -9
  16. package/lib/esm/shapes/PathList.js.map +1 -1
  17. package/lib/esm/shapes/PathNode.d.ts +1 -3
  18. package/lib/esm/shapes/PathNode.js +6 -8
  19. package/lib/esm/shapes/PathNode.js.map +1 -1
  20. package/lib/esm/shapes/SHACL.d.ts +15 -13
  21. package/lib/esm/shapes/SHACL.js +8 -0
  22. package/lib/esm/shapes/SHACL.js.map +1 -1
  23. package/lib/esm/shapes/nodeShapeData.d.ts +4 -1
  24. package/lib/esm/shapes/nodeShapeData.js.map +1 -1
  25. package/lib/esm/shapes/singleOwnerConstraint.d.ts +5 -7
  26. package/lib/esm/shapes/singleOwnerConstraint.js +65 -21
  27. package/lib/esm/shapes/singleOwnerConstraint.js.map +1 -1
  28. package/lib/esm/shapes/syncShapes.d.ts +54 -3
  29. package/lib/esm/shapes/syncShapes.js +141 -13
  30. package/lib/esm/shapes/syncShapes.js.map +1 -1
  31. package/lib/esm/sparql/irToAlgebra.d.ts +15 -38
  32. package/lib/esm/sparql/irToAlgebra.js +406 -391
  33. package/lib/esm/sparql/irToAlgebra.js.map +1 -1
  34. package/lib/esm/sparql/ownedLinkCheck.d.ts +6 -10
  35. package/lib/esm/sparql/ownedLinkCheck.js +10 -11
  36. package/lib/esm/sparql/ownedLinkCheck.js.map +1 -1
  37. package/lib/esm/utils/Package.d.ts +3 -2
  38. package/lib/esm/utils/Package.js +21 -8
  39. package/lib/esm/utils/Package.js.map +1 -1
  40. package/lib/esm/utils/sha256.d.ts +8 -0
  41. package/lib/esm/utils/sha256.js +80 -0
  42. package/lib/esm/utils/sha256.js.map +1 -0
  43. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"syncShapes.js","sourceRoot":"","sources":["../../../src/shapes/syncShapes.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;GAIG;AACH,OAAO,EAAC,kBAAkB,EAAE,aAAa,EAAC,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAC,SAAS,EAAC,MAAM,YAAY,CAAC;AACrC,OAAO,EACL,uBAAuB,GAGxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAC,aAAa,EAAC,MAAM,6BAA6B,CAAC;AAE1D,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAC;AAClC,OAAO,EAAC,uBAAuB,EAAC,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAC,2BAA2B,EAAC,MAAM,4BAA4B,CAAC;AAEvE;;;GAGG;AACH,MAAM,iBAAiB,GAAG,eAAe,CAAC;AAE1C;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,EAAqB,EAAE,QAAgB;IAC5E,MAAM,KAAK,GAAG,GAAG,QAAQ,IAAI,EAAE,CAAC,KAAK,EAAE,CAAC;IACxC,MAAM,CAAC,GAA4B;QACjC,IAAI,EAAE,KAAK;QACX,IAAI,EAAE,uBAAuB,CAAC,EAAE,CAAC,IAAI,CAAC;KACvC,CAAC;IACF,+EAA+E;IAC/E,+EAA+E;IAC/E,sCAAsC;IACtC,EAAE;IACF,8EAA8E;IAC9E,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AAE,CAAC,CAAC,CAAC;IAC3E,OAAO,cAAc,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport {getAllShapeClasses, getShapeClass} from '../utils/ShapeClass.js';\nimport {NodeShape} from './SHACL.js';\nimport {\n getUniquePropertyShapes,\n type NodeShapeData,\n type PropertyShapeData,\n} from './nodeShapeData.js';\nimport {Shape} from './Shape.js';\nimport {DeleteBuilder} from '../queries/DeleteBuilder.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {rdfList} from './List.js';\nimport {serializePathToNodeData} from './serializePathToNodeData.js';\nimport {buildSingleOwnerConstraints} from './singleOwnerConstraint.js';\n\n/**\n * The npm scope of framework shapes (NodeShape/PropertyShape/List/PathNode/Shape) that\n * describe the meta-model itself and must never be synced as user data.\n */\nconst FRAMEWORK_PACKAGE = '@_linked/core';\n\n/**\n * Build the create-pipeline data object for a single PropertyShape (flattened under shapeIri).\n *\n * @internal Exported for tests only — not part of the public API.\n */\nexport function buildPropertyShapeData(ps: PropertyShapeData, shapeIri: string): Record<string, unknown> {\n const psIri = `${shapeIri}/${ps.label}`;\n const d: Record<string, unknown> = {\n __id: psIri,\n path: serializePathToNodeData(ps.path),\n };\n // `rdfs:label` — the DSL label, i.e. the accessor name the property is reached\n // by in code (`person.memberships`). It is NOT `sh:name`, written below, which\n // is a human-readable display string.\n //\n // Without this the label is only ever implied by `psIri`, and a reader has to\n // re-derive one from the path's local part. That works right up until the two\n // differ — `@_linked/org` declares `memberships` on the path `org:hasMembership`\n // — at which point the catalog reports `hasMembership`, the query proxy indexes\n // the shape with it, and the class (which only knows `memberships`) throws.\n // Readers already prefer a stored label and fall back to the path, so writing it\n // is the whole fix; old catalogs keep working via that fallback.\n if (ps.label) d.label = ps.label;\n if (ps.nodeKind) d.nodeKind = ps.nodeKind;\n if (ps.datatype) d.datatype = ps.datatype;\n if (typeof ps.minCount === 'number') d.minCount = ps.minCount;\n if (typeof ps.maxCount === 'number') d.maxCount = ps.maxCount;\n if (ps.name) d.name = ps.name;\n if (ps.description) d.description = ps.description;\n if (typeof ps.order === 'number') d.order = ps.order;\n if (ps.group) d.group = ps.group;\n if (typeof ps.displayRank === 'number') d.displayRank = ps.displayRank;\n if (ps.displayHidden !== undefined) d.displayHidden = ps.displayHidden;\n if (ps.class) d.class = ps.class;\n if (ps.in) d.in = rdfList(ps.in, {base: `${psIri}/in`});\n if (ps.equalsConstraint) d.equalsConstraint = ps.equalsConstraint;\n if (ps.disjoint) d.disjoint = ps.disjoint;\n if (ps.lessThan) d.lessThan = ps.lessThan;\n if (ps.lessThanOrEquals) d.lessThanOrEquals = ps.lessThanOrEquals;\n if (ps.minInclusive !== undefined) d.minInclusive = ps.minInclusive;\n if (ps.maxInclusive !== undefined) d.maxInclusive = ps.maxInclusive;\n if (ps.minExclusive !== undefined) d.minExclusive = ps.minExclusive;\n if (ps.maxExclusive !== undefined) d.maxExclusive = ps.maxExclusive;\n if (typeof ps.minLength === 'number') d.minLength = ps.minLength;\n if (typeof ps.maxLength === 'number') d.maxLength = ps.maxLength;\n // sh:pattern is serialized as its regex source string.\n if (ps.pattern) d.pattern = ps.pattern.source;\n if (ps.hasValueConstraint !== undefined) d.hasValue = ps.hasValueConstraint;\n if (ps.valueShape) d.valueShape = ps.valueShape;\n if (ps.contains) d.contains = true;\n return d;\n}\n\n/** Build the create-pipeline data object for a NodeShape and its (flattened) property shapes. */\nfunction buildNodeShapeData(nodeShape: NodeShapeData, shapeIri: string): Record<string, unknown> {\n const d: Record<string, unknown> = {};\n if (nodeShape.targetClass) d.targetClass = nodeShape.targetClass;\n if (nodeShape.description) d.description = nodeShape.description;\n if (nodeShape.extends) d.extends = nodeShape.extends;\n if (nodeShape.dependent) d.dependent = true;\n if (nodeShape.closed !== undefined) d.closed = nodeShape.closed;\n if (nodeShape.ignoredProperties && nodeShape.ignoredProperties.length) {\n d.ignoredProperties = nodeShape.ignoredProperties;\n }\n // Flatten: emit own + inherited property shapes (deduped by label) under this shape.\n d.properties = getUniquePropertyShapes(nodeShape).map((ps) =>\n buildPropertyShapeData(ps, shapeIri),\n );\n // The single-owner constraints of the shape's own `contains` properties, owned through\n // `core:generatedShape` and written nested in the same create with their fixed IRIs.\n const generated = buildSingleOwnerConstraints(nodeShape, shapeIri);\n if (generated.length > 0) {\n d.generatedShapes = generated.map(({iri, data}) => ({__id: iri, ...data}));\n }\n return d;\n}\n\n/**\n * The per-shape `delete → create` thunk shared by `syncShapes()` and `syncShape()`: exactly two\n * requests. The delete cascade-cleans the shape's old property-shape / list / path subtrees; the\n * create rebuilds them.\n *\n * The single-owner constraints generated from the shape's own `contains` properties\n * (`${iri}/${label}.singleOwner`, see `singleOwnerConstraint.ts`) are owned by the shape through\n * `core:generatedShape` (a `contains` property with value shape NodeShape). The delete removes\n * each one's own triples (the immediate owned-child block) and their property shapes and path\n * nodes (the dependent cascade); the create writes the current ones nested, in the same request\n * as the shape. A removed or renamed accessor therefore loses its constraint on the next sync,\n * and a NodeShape the shape does not own is never touched.\n *\n * `ds` (optional) targets an explicit dataset — both requests run against it instead of the\n * global router. Omitted → today's global behavior.\n */\nfunction buildSyncThunk(nodeShape: NodeShapeData, iri: string, ds?: IDataset): () => Promise<void> {\n return async () => {\n // Build the data fresh on each invocation, so every run writes from the current\n // shape metadata.\n const data = buildNodeShapeData(nodeShape, iri);\n await DeleteBuilder.from(NodeShape, {id: iri}).exec(ds);\n await (NodeShape.create(data as never).withId(iri) as unknown as {\n exec: (target?: IDataset) => Promise<unknown>;\n }).exec(ds);\n };\n}\n\n/** The generated single-owner shape IRIs a code shape writes. */\nfunction generatedIrisOf(nodeShape: NodeShapeData, iri: string): string[] {\n return buildSingleOwnerConstraints(nodeShape, iri).map((c) => c.iri);\n}\n\n/** Throw when a registered shape IRI equals one of a shape's generated single-owner IRIs. */\nfunction assertNoGeneratedIriCollision(\n nodeShape: NodeShapeData,\n iri: string,\n isRegistered: (iri: string) => boolean,\n): void {\n for (const generated of generatedIrisOf(nodeShape, iri)) {\n if (isRegistered(generated)) {\n throw new Error(`Shape IRI ${generated} collides with a generated single-owner shape`);\n }\n }\n}\n\n/** Options controlling how {@link syncShapes} treats store shapes that are not in code. */\nexport interface SyncShapesOptions {\n /**\n * How to treat NodeShapes present in the store but not in the current process's code:\n * - `'none'` (default) — never prune; purely additive (delete→recreate the code shapes, touch\n * nothing else). The only mode that is safe when the process has loaded a *subset* of the\n * shapes in the dataset, or when the dataset has more than one writer.\n * - `'all'` — prune every store-only shape as an orphan. Only correct when this process has\n * loaded **every** shape the dataset should hold and is its **only** writer; \"not registered\n * here\" is then taken to mean \"deleted from code\".\n * - `'ownedNamespaces'` — prune a store-only shape ONLY if its IRI falls within a namespace\n * this process actually writes (the package-namespace of one of its code-registered shapes,\n * i.e. the IRI prefix up to the last `/` or `#`). Protects other writers' packages (arch-04:\n * one app-data dataset, several writers), but NOT the rest of a package the process only\n * partially loaded — the namespace is the whole package, so a deep import of one shape file\n * still claims all of it.\n *\n * `'all'` and `'ownedNamespaces'` are destructive and must be requested explicitly.\n */\n orphanScope?: 'all' | 'ownedNamespaces' | 'none';\n}\n\n/** The owning namespace of a shape IRI — everything up to and including the last `/` or `#`. */\nfunction shapeNamespace(iri: string): string {\n const cut = Math.max(iri.lastIndexOf('/'), iri.lastIndexOf('#'));\n return cut >= 0 ? iri.slice(0, cut + 1) : iri;\n}\n\n/**\n * Plan an idempotent sync of all code-registered (non-framework) NodeShapes into the store as\n * SHACL data — the forward (code → graph) materialization of arch-05 \"code is canonical\".\n *\n * Returns built-but-unexecuted thunks; the caller controls execution and batching:\n * ```ts\n * await Promise.all((await syncShapes()).map((run) => run()));\n * ```\n * Each in-code shape's thunk runs `delete → create` in order (the delete cascade-cleans the old\n * property shapes / list / path subtrees via the containment cascade, the create rebuilds them).\n *\n * **Shapes in the store but not registered in this process are left alone by default**\n * (`orphanScope: 'none'`). The registry only holds what this process happened to import, and\n * that is routinely a subset of what the dataset holds: shapes are deep-importable one file at a\n * time, and an app-data dataset also holds shapes other writers materialized (CN's\n * `bindShape` / `enableCapability`). \"Not registered here\" therefore does not mean \"deleted from\n * code\". Measured against a dataset holding the 36 `@_linked/schema` shapes: a process that\n * imported only `@_linked/schema/shapes/Thing` (11 shapes registered) deleted the other 25 under\n * both `'all'` and `'ownedNamespaces'`, and a process that imported no shapes deleted all 36.\n *\n * Pruning is opt-in via `options.orphanScope` (see {@link SyncShapesOptions}): pass `'all'` only\n * from a process that has loaded every shape the dataset should hold and is its sole writer, and\n * `'ownedNamespaces'` only when it has loaded every shape of each package it registers. Pruned\n * orphans are deleted with their owned subtree. Pruning reads the existing shape IRIs first;\n * with `'none'` no read is made.\n *\n * `ds` (optional) targets an explicit dataset instead of the global router. It is a **plan-time**\n * parameter: it feeds both the orphan-detection read (so orphans are computed against the same\n * store they'll be pruned from) and every delete/create thunk. Omitted → the global router;\n * the returned thunks stay nullary either way.\n */\nexport async function syncShapes(\n ds?: IDataset,\n options?: SyncShapesOptions,\n): Promise<Array<() => Promise<void>>> {\n const orphanScope = options?.orphanScope ?? 'none';\n // 1. Enumerate code-registered user shapes (exclude framework/meta shapes).\n const userShapes: Array<{iri: string; nodeShape: NodeShapeData}> = [];\n for (const [iri, shapeClass] of getAllShapeClasses()) {\n if (!shapeClass?.shape) continue;\n const pkg = (shapeClass as {packageName?: string}).packageName;\n // Skip framework/meta shapes: the core package, and the base `Shape` which is registered\n // directly (no applyLinkedShape) and therefore carries no packageName.\n if (!pkg || pkg === FRAMEWORK_PACKAGE) continue;\n userShapes.push({iri, nodeShape: shapeClass.shape});\n }\n const localShapeIris = new Set(userShapes.map((s) => s.iri));\n for (const {iri, nodeShape} of userShapes) {\n assertNoGeneratedIriCollision(nodeShape, iri, (id) => localShapeIris.has(id));\n }\n // The generated single-owner shapes of in-code shapes are written by the same thunks, so they\n // are never orphans. Derived in memory from the same function that builds them; a stale\n // generated shape (removed accessor or shape) is not protected and goes with its owner's\n // delete, through the `core:generatedShape` cascade.\n for (const {iri, nodeShape} of userShapes) {\n for (const generated of generatedIrisOf(nodeShape, iri)) localShapeIris.add(generated);\n }\n // Namespaces this process actually writes — the ownership scope for `'ownedNamespaces'` pruning.\n const ownedNamespaces = new Set(userShapes.map((s) => shapeNamespace(s.iri)));\n\n const thunks: Array<() => Promise<void>> = [];\n\n // 2. Per in-code shape: delete (cascade) then recreate.\n for (const {iri, nodeShape} of userShapes) {\n thunks.push(buildSyncThunk(nodeShape, iri, ds));\n }\n\n // 3. Orphan sweep (unless disabled). Identity-read existing NodeShape IRIs (ids only). Must hit\n // the same `ds` the thunks target, or orphans get computed against the wrong store.\n if (orphanScope !== 'none') {\n const existingRows = (await (NodeShape as unknown as {\n select: () => {exec: (target?: IDataset) => Promise<Array<{id: string}>>};\n }).select().exec(ds)) as Array<{id: string}>;\n\n // Orphan shapes (in store, not in code) → delete (cascade cleans their owned subtree). In\n // `'ownedNamespaces'` mode, only shapes within a namespace this process writes are eligible —\n // other writers' shapes (different package namespace) are left untouched.\n for (const {id: iri} of existingRows) {\n if (localShapeIris.has(iri)) continue;\n if (orphanScope === 'ownedNamespaces' && !ownedNamespaces.has(shapeNamespace(iri))) {\n continue;\n }\n thunks.push(() =>\n (DeleteBuilder.from(NodeShape, {id: iri}).exec(ds) as Promise<unknown>).then(\n () => undefined,\n ),\n );\n }\n }\n\n return thunks;\n}\n\n/**\n * Plan an idempotent sync of ONE code-registered NodeShape into the store as SHACL data.\n *\n * Scoped counterpart to {@link syncShapes}: materializes a single shape (delete → recreate, so the\n * delete cascade-cleans the old property-shape / list / path subtrees and the create rebuilds them)\n * and does NOT run the store-wide orphan sweep — other shapes in the store are untouched.\n *\n * @param target a shape class (e.g. `Person`) or its NodeShape IRI string. An IRI is resolved to\n * its registered class via `getShapeClass`; the shape must be code-registered.\n * @param ds optional explicit dataset to materialize into (a store or a router) — both the delete\n * and the create run against it instead of the global router. Omitted → global behavior.\n * @returns a single unexecuted thunk (consistent with {@link syncShapes}), so callers can batch\n * several together — e.g. a shape plus its referenced object-property shapes:\n * `await Promise.all([syncShape(Person), syncShape(Address)].map((run) => run()))`.\n * @throws if `target` is a framework/meta shape, is not registered, or has no `.shape`.\n */\nexport function syncShape(target: typeof Shape | string, ds?: IDataset): () => Promise<void> {\n // Normalize target → its registered shape class.\n const cls =\n typeof target === 'string' ? getShapeClass(target) : (target as typeof Shape);\n if (typeof target === 'string' && !cls) {\n throw new Error(`syncShape: no registered shape for IRI ${target}`);\n }\n const nodeShape = cls?.shape;\n if (!nodeShape) {\n throw new Error(\n typeof target === 'string'\n ? `syncShape: no registered shape for IRI ${target}`\n : `syncShape: shape class has no static .shape`,\n );\n }\n const iri = nodeShape.id;\n\n // Never materialize a framework/meta shape as user data — same invariant syncShapes() enforces\n // by skipping (the base Shape carries no packageName).\n const pkg = (cls as {packageName?: string}).packageName;\n if (!pkg || pkg === FRAMEWORK_PACKAGE) {\n throw new Error(`syncShape: refusing to sync framework/meta shape ${iri}`);\n }\n\n assertNoGeneratedIriCollision(nodeShape, iri, (id) => !!getShapeClass(id));\n return buildSyncThunk(nodeShape, iri, ds);\n}\n"]}
1
+ {"version":3,"file":"syncShapes.js","sourceRoot":"","sources":["../../../src/shapes/syncShapes.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;GAIG;AACH,OAAO,EAAC,kBAAkB,EAAE,aAAa,EAAC,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAC,SAAS,EAAC,MAAM,YAAY,CAAC;AACrC,OAAO,EACL,uBAAuB,GAGxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAC,aAAa,EAAC,MAAM,6BAA6B,CAAC;AAE1D,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAC;AAClC,OAAO,EAAC,uBAAuB,EAAC,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAC,2B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+F;IAC/F,uDAAuD;IACvD,MAAM,GAAG,GAAI,GAA8B,CAAC,WAAW,CAAC;IACxD,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,iBAAiB,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,oDAAoD,GAAG,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,6BAA6B,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3E,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,KAAK;QAAE,OAAO,cAAc,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;IAC9D,OAAO,GAAS,EAAE;QAChB,MAAM,MAAM,GAAG,MAAM,gBAAgB,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;QACjD,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,aAAa,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,IAAI;YAAE,OAAO;QACnE,MAAM,UAAU,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;IACvC,CAAC,CAAA,CAAC;AACJ,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport {getAllShapeClasses, getShapeClass} from '../utils/ShapeClass.js';\nimport {NodeShape} from './SHACL.js';\nimport {\n getUniquePropertyShapes,\n type NodeShapeData,\n type PropertyShapeData,\n} from './nodeShapeData.js';\nimport {Shape} from './Shape.js';\nimport {DeleteBuilder} from '../queries/DeleteBuilder.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {rdfList} from './List.js';\nimport {serializePathToNodeData} from './serializePathToNodeData.js';\nimport {buildSingleOwnerConstraints} from './singleOwnerConstraint.js';\nimport {QueryBuilder} from '../queries/QueryBuilder.js';\nimport {sha256Hex} from '../utils/sha256.js';\n\n/**\n * The npm scope of framework shapes (NodeShape/PropertyShape/List/PathNode/Shape) that\n * describe the meta-model itself and must never be synced as user data.\n */\nconst FRAMEWORK_PACKAGE = '@_linked/core';\n\n/**\n * Build the create-pipeline data object for a single PropertyShape (flattened under shapeIri).\n *\n * @internal Exported for tests only — not part of the public API.\n */\nexport function buildPropertyShapeData(ps: PropertyShapeData, shapeIri: string): Record<string, unknown> {\n const psIri = `${shapeIri}/${ps.label}`;\n const d: Record<string, unknown> = {\n __id: psIri,\n path: serializePathToNodeData(ps.path),\n };\n // `rdfs:label` — the DSL label, i.e. the accessor name the property is reached\n // by in code (`person.memberships`). It is NOT `sh:name`, written below, which\n // is a human-readable display string.\n //\n // Without this the label is only ever implied by `psIri`, and a reader has to\n // re-derive one from the path's local part. That works right up until the two\n // differ — `@_linked/org` declares `memberships` on the path `org:hasMembership`\n // — at which point the catalog reports `hasMembership`, the query proxy indexes\n // the shape with it, and the class (which only knows `memberships`) throws.\n // Readers already prefer a stored label and fall back to the path, so writing it\n // is the whole fix; old catalogs keep working via that fallback.\n if (ps.label) d.label = ps.label;\n if (ps.nodeKind) d.nodeKind = ps.nodeKind;\n if (ps.datatype) d.datatype = ps.datatype;\n if (typeof ps.minCount === 'number') d.minCount = ps.minCount;\n if (typeof ps.maxCount === 'number') d.maxCount = ps.maxCount;\n if (ps.name) d.name = ps.name;\n if (ps.description) d.description = ps.description;\n if (typeof ps.order === 'number') d.order = ps.order;\n if (ps.group) d.group = ps.group;\n if (typeof ps.displayRank === 'number') d.displayRank = ps.displayRank;\n if (ps.displayHidden !== undefined) d.displayHidden = ps.displayHidden;\n if (ps.class) d.class = ps.class;\n if (ps.in) d.in = rdfList(ps.in, {base: `${psIri}/in`});\n if (ps.equalsConstraint) d.equalsConstraint = ps.equalsConstraint;\n if (ps.disjoint) d.disjoint = ps.disjoint;\n if (ps.lessThan) d.lessThan = ps.lessThan;\n if (ps.lessThanOrEquals) d.lessThanOrEquals = ps.lessThanOrEquals;\n if (ps.minInclusive !== undefined) d.minInclusive = ps.minInclusive;\n if (ps.maxInclusive !== undefined) d.maxInclusive = ps.maxInclusive;\n if (ps.minExclusive !== undefined) d.minExclusive = ps.minExclusive;\n if (ps.maxExclusive !== undefined) d.maxExclusive = ps.maxExclusive;\n if (typeof ps.minLength === 'number') d.minLength = ps.minLength;\n if (typeof ps.maxLength === 'number') d.maxLength = ps.maxLength;\n // sh:pattern is serialized as its regex source string.\n if (ps.pattern) d.pattern = ps.pattern.source;\n if (ps.hasValueConstraint !== undefined) d.hasValue = ps.hasValueConstraint;\n if (ps.valueShape) d.valueShape = ps.valueShape;\n if (ps.contains) d.contains = true;\n return d;\n}\n\n/** Build the create-pipeline data object for a NodeShape and its (flattened) property shapes. */\nfunction buildNodeShapeData(nodeShape: NodeShapeData, shapeIri: string): Record<string, unknown> {\n const d: Record<string, unknown> = {};\n if (nodeShape.targetClass) d.targetClass = nodeShape.targetClass;\n if (nodeShape.description) d.description = nodeShape.description;\n if (nodeShape.extends) d.extends = nodeShape.extends;\n if (nodeShape.dependent) d.dependent = true;\n if (nodeShape.closed !== undefined) d.closed = nodeShape.closed;\n if (nodeShape.ignoredProperties && nodeShape.ignoredProperties.length) {\n d.ignoredProperties = nodeShape.ignoredProperties;\n }\n // Flatten: emit own + inherited property shapes (deduped by label) under this shape.\n d.properties = getUniquePropertyShapes(nodeShape).map((ps) =>\n buildPropertyShapeData(ps, shapeIri),\n );\n // The single-owner constraints of the shape's own `contains` properties, owned through\n // `core:generatedShape` and written nested in the same create with their fixed IRIs.\n const generated = buildSingleOwnerConstraints(nodeShape, shapeIri);\n if (generated.length > 0) {\n d.generatedShapes = generated.map(({iri, data}) => ({__id: iri, ...data}));\n }\n return d;\n}\n\n/**\n * Version of the {@link shapeSyncHash} input. Bump it whenever core changes the SHACL it writes\n * for a shape (a serialization change that the create data itself does not show), so every stored\n * shape is rewritten once by the next sync. Without a bump, stores keep the old triples: their\n * stored hashes still match, so the sync skips them.\n *\n * Enforced by `shape-sync-output-equivalence.test.ts`: its golden SHACL output is recorded in\n * `SHAPE_HASH_LEDGER` with the version it was generated for, and regenerating the golden without\n * bumping this constant fails that test. To change the output: bump this by one, update the\n * golden, and append `{version, goldenDigest}` to the ledger (never edit an existing entry).\n *\n * @internal Exported for tests only — not part of the public API.\n */\nexport const SHAPE_HASH_VERSION = 1;\n\n/**\n * A canonical string for create-pipeline data: equal for equal data, independent of object key\n * order and of the order of array values.\n *\n * Arrays are sorted because in create data an array is always a multi-valued property (a set of\n * RDF values: `properties`, `generatedShapes`, `targetObjectsOf`, …). Ordered `rdf:List`s\n * (`sh:in`, sequence and alternative paths, `sh:or`) are nested `first`/`rest` objects, so their\n * order is kept by the structure. A shape class value (`shape: List`) is written as its NodeShape\n * IRI. Values without ids (blank nodes once written) are compared by structure, so no blank-node\n * label is ever part of the input.\n */\nfunction canonicalize(value: unknown): string {\n if (value === null || value === undefined) return 'null';\n switch (typeof value) {\n case 'string':\n return JSON.stringify(value);\n case 'number':\n return `n:${Object.is(value, -0) ? '0' : String(value)}`;\n case 'boolean':\n return `b:${value}`;\n case 'bigint':\n return `i:${value.toString()}`;\n case 'function': {\n const shapeId = (value as {shape?: {id?: string}}).shape?.id;\n return `c:${JSON.stringify(shapeId ?? (value as {name?: string}).name ?? '')}`;\n }\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalize).sort().join(',')}]`;\n }\n if (value instanceof Date) return `d:${value.toISOString()}`;\n if (value instanceof RegExp) return `r:${JSON.stringify(value.source)}/${value.flags}`;\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter((k) => record[k] !== undefined)\n .sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(record[k])}`).join(',')}}`;\n}\n\n/**\n * The content hash shape sync stores on a NodeShape as `core:shapeHash`: SHA-256 (hex) of the\n * canonical form of the shape IRI and the exact create data the sync writes for it — the\n * NodeShape, its flattened own + inherited property shapes, their `sh:in` lists and paths, and\n * the generated single-owner shapes it owns (whose owner classes come from the registered\n * sub-shapes, so registering a new sub-shape changes the hash of the declaring shape).\n *\n * Deterministic across processes, runtimes and Node versions: no blank-node labels, no object key\n * order, no array order (see {@link canonicalize}).\n *\n * @internal Exported for tests only — not part of the public API.\n */\nexport function shapeSyncHash(data: Record<string, unknown>, shapeIri: string): string {\n return sha256Hex(`linked-shape-sync/${SHAPE_HASH_VERSION}\\n${canonicalize({iri: shapeIri, data})}`);\n}\n\n/** The create data and its content hash for one shape, as the sync writes it. */\nfunction buildSyncData(\n nodeShape: NodeShapeData,\n iri: string,\n): {data: Record<string, unknown>; hash: string} {\n const data = buildNodeShapeData(nodeShape, iri);\n return {data, hash: shapeSyncHash(data, iri)};\n}\n\n/**\n * The stored `core:shapeHash` of each of `iris` that exists as a NodeShape, in one select. A shape\n * that is absent, or stored without a hash (written before hashes existed), is missing from the\n * map. `ds` targets an explicit dataset, as for the writes.\n */\nasync function readStoredHashes(iris: string[], ds?: IDataset): Promise<Map<string, string>> {\n const stored = new Map<string, string>();\n if (iris.length === 0) return stored;\n const rows = (await (QueryBuilder.from(NodeShape).select(['shapeHash']).forAll(iris) as unknown as {\n exec: (target?: IDataset) => Promise<Array<{id: string; shapeHash?: unknown}> | null>;\n }).exec(ds)) ?? [];\n for (const row of rows) {\n if (row && typeof row.shapeHash === 'string') stored.set(row.id, row.shapeHash);\n }\n return stored;\n}\n\n/**\n * The per-shape `delete → create` thunk shared by `syncShapes()` and `syncShape()`: exactly two\n * requests. The delete cascade-cleans the shape's old property-shape / list / path subtrees; the\n * create rebuilds them, and stores the content hash (`core:shapeHash`) of what it wrote on the\n * NodeShape so a later sync can skip the shape while it is unchanged.\n *\n * The single-owner constraints generated from the shape's own `contains` properties\n * (`${iri}/${label}.singleOwner`, see `singleOwnerConstraint.ts`) are owned by the shape through\n * `core:generatedShape` (a `contains` property with value shape NodeShape). The delete removes\n * them and their property shapes through the owned walk, and their blank path and qualified-shape\n * nodes through the blank-node cascade; the create writes the current ones nested, in the same request\n * as the shape. A removed or renamed accessor therefore loses its constraint on the next sync,\n * and a NodeShape the shape does not own is never touched.\n *\n * `ds` (optional) targets an explicit dataset — both requests run against it instead of the\n * global router. Omitted → today's global behavior.\n */\nfunction buildSyncThunk(nodeShape: NodeShapeData, iri: string, ds?: IDataset): () => Promise<void> {\n // `writeShape` builds the data fresh on each invocation, so every run writes from the current\n // shape metadata, and the hash stored with it always describes what was written.\n return () => writeShape(nodeShape, iri, ds);\n}\n\n/** Delete (cascade) then create one shape, storing the hash of the written data. */\nasync function writeShape(nodeShape: NodeShapeData, iri: string, ds?: IDataset): Promise<void> {\n const {data, hash} = buildSyncData(nodeShape, iri);\n await DeleteBuilder.from(NodeShape, {id: iri}).exec(ds);\n await (NodeShape.create({...data, shapeHash: hash} as never).withId(iri) as unknown as {\n exec: (target?: IDataset) => Promise<unknown>;\n }).exec(ds);\n}\n\n/** The generated single-owner shape IRIs a code shape writes. */\nfunction generatedIrisOf(nodeShape: NodeShapeData, iri: string): string[] {\n return buildSingleOwnerConstraints(nodeShape, iri).map((c) => c.iri);\n}\n\n/** Throw when a registered shape IRI equals one of a shape's generated single-owner IRIs. */\nfunction assertNoGeneratedIriCollision(\n nodeShape: NodeShapeData,\n iri: string,\n isRegistered: (iri: string) => boolean,\n): void {\n for (const generated of generatedIrisOf(nodeShape, iri)) {\n if (isRegistered(generated)) {\n throw new Error(`Shape IRI ${generated} collides with a generated single-owner shape`);\n }\n }\n}\n\n/** Options controlling how {@link syncShapes} treats store shapes that are not in code. */\nexport interface SyncShapesOptions {\n /**\n * How to treat NodeShapes present in the store but not in the current process's code:\n * - `'none'` (default) — never prune; purely additive (delete→recreate the code shapes, touch\n * nothing else). The only mode that is safe when the process has loaded a *subset* of the\n * shapes in the dataset, or when the dataset has more than one writer.\n * - `'all'` — prune every store-only shape as an orphan. Only correct when this process has\n * loaded **every** shape the dataset should hold and is its **only** writer; \"not registered\n * here\" is then taken to mean \"deleted from code\".\n * - `'ownedNamespaces'` — prune a store-only shape ONLY if its IRI falls within a namespace\n * this process actually writes (the package-namespace of one of its code-registered shapes,\n * i.e. the IRI prefix up to the last `/` or `#`). Protects other writers' packages (arch-04:\n * one app-data dataset, several writers), but NOT the rest of a package the process only\n * partially loaded — the namespace is the whole package, so a deep import of one shape file\n * still claims all of it.\n *\n * `'all'` and `'ownedNamespaces'` are destructive and must be requested explicitly.\n */\n orphanScope?: 'all' | 'ownedNamespaces' | 'none';\n /**\n * Rewrite every code shape, even one whose stored `core:shapeHash` matches. Default `false`:\n * a shape is rewritten only when its hash differs or is missing. Use it to repair a shape\n * whose stored subtree was edited or partly deleted outside shape sync (the hash describes\n * what sync last wrote, not what is in the store now).\n */\n force?: boolean;\n}\n\n/** Options for {@link syncShape}. */\nexport interface SyncShapeOptions {\n /** Rewrite the shape even when its stored `core:shapeHash` matches. See {@link SyncShapesOptions.force}. */\n force?: boolean;\n}\n\n/** The owning namespace of a shape IRI — everything up to and including the last `/` or `#`. */\nfunction shapeNamespace(iri: string): string {\n const cut = Math.max(iri.lastIndexOf('/'), iri.lastIndexOf('#'));\n return cut >= 0 ? iri.slice(0, cut + 1) : iri;\n}\n\n/**\n * Plan an idempotent sync of all code-registered (non-framework) NodeShapes into the store as\n * SHACL data — the forward (code → graph) materialization of arch-05 \"code is canonical\".\n *\n * Returns built-but-unexecuted thunks; the caller controls execution and batching:\n * ```ts\n * await Promise.all((await syncShapes()).map((run) => run()));\n * ```\n * Each in-code shape's thunk runs `delete → create` in order (the delete cascade-cleans the old\n * property shapes / list / path subtrees via the containment cascade, the create rebuilds them).\n *\n * **Unchanged shapes are skipped.** The create stores a content hash of everything it writes for\n * the shape on the NodeShape (`core:shapeHash`, see {@link shapeSyncHash}). The plan reads the\n * stored hashes of all code shapes in one select and builds a thunk only for a shape whose hash\n * is missing (never synced, or synced before hashes existed) or differs. Syncing an unchanged\n * app therefore returns no write thunks, and the length of the plan is the number of shapes\n * actually written plus the pruned orphans. The hash records what sync last wrote, not what the\n * store holds now: a subtree edited or partly deleted by another writer while the NodeShape and\n * its hash survive is not detected. `options.force` rewrites every code shape.\n *\n * **Shapes in the store but not registered in this process are left alone by default**\n * (`orphanScope: 'none'`). The registry only holds what this process happened to import, and\n * that is routinely a subset of what the dataset holds: shapes are deep-importable one file at a\n * time, and an app-data dataset also holds shapes other writers materialized (CN's\n * `bindShape` / `enableCapability`). \"Not registered here\" therefore does not mean \"deleted from\n * code\". Measured against a dataset holding the 36 `@_linked/schema` shapes: a process that\n * imported only `@_linked/schema/shapes/Thing` (11 shapes registered) deleted the other 25 under\n * both `'all'` and `'ownedNamespaces'`, and a process that imported no shapes deleted all 36.\n *\n * Pruning is opt-in via `options.orphanScope` (see {@link SyncShapesOptions}): pass `'all'` only\n * from a process that has loaded every shape the dataset should hold and is its sole writer, and\n * `'ownedNamespaces'` only when it has loaded every shape of each package it registers. Pruned\n * orphans are deleted with their owned subtree. Pruning reads the existing shape IRIs first;\n * with `'none'` no read is made.\n *\n * `ds` (optional) targets an explicit dataset instead of the global router. It is a **plan-time**\n * parameter: it feeds the stored-hash read and the orphan-detection read (so both are computed\n * against the same store they'll be written to) and every delete/create thunk. Omitted → the global router;\n * the returned thunks stay nullary either way.\n */\nexport async function syncShapes(\n ds?: IDataset,\n options?: SyncShapesOptions,\n): Promise<Array<() => Promise<void>>> {\n const orphanScope = options?.orphanScope ?? 'none';\n // 1. Enumerate code-registered user shapes (exclude framework/meta shapes).\n const userShapes: Array<{iri: string; nodeShape: NodeShapeData}> = [];\n for (const [iri, shapeClass] of getAllShapeClasses()) {\n if (!shapeClass?.shape) continue;\n const pkg = (shapeClass as {packageName?: string}).packageName;\n // Skip framework/meta shapes: the core package, and the base `Shape` which is registered\n // directly (no applyLinkedShape) and therefore carries no packageName.\n if (!pkg || pkg === FRAMEWORK_PACKAGE) continue;\n userShapes.push({iri, nodeShape: shapeClass.shape});\n }\n const localShapeIris = new Set(userShapes.map((s) => s.iri));\n for (const {iri, nodeShape} of userShapes) {\n assertNoGeneratedIriCollision(nodeShape, iri, (id) => localShapeIris.has(id));\n }\n // The generated single-owner shapes of in-code shapes are written by the same thunks, so they\n // are never orphans. Derived in memory from the same function that builds them; a stale\n // generated shape (removed accessor or shape) is not protected and goes with its owner's\n // delete, through the `core:generatedShape` cascade.\n for (const {iri, nodeShape} of userShapes) {\n for (const generated of generatedIrisOf(nodeShape, iri)) localShapeIris.add(generated);\n }\n // Namespaces this process actually writes — the ownership scope for `'ownedNamespaces'` pruning.\n const ownedNamespaces = new Set(userShapes.map((s) => shapeNamespace(s.iri)));\n\n const thunks: Array<() => Promise<void>> = [];\n\n // 2. Per in-code shape whose stored content hash is missing or differs: delete (cascade) then\n // recreate. An unchanged shape gets no thunk, so syncing an unchanged app writes nothing.\n // The stored hashes are read in one select, against the same `ds` the thunks target.\n const storedHashes = options?.force\n ? new Map<string, string>()\n : await readStoredHashes(userShapes.map((s) => s.iri), ds);\n for (const {iri, nodeShape} of userShapes) {\n if (!options?.force && storedHashes.get(iri) === buildSyncData(nodeShape, iri).hash) continue;\n thunks.push(buildSyncThunk(nodeShape, iri, ds));\n }\n\n // 3. Orphan sweep (unless disabled). Identity-read existing NodeShape IRIs (ids only). Must hit\n // the same `ds` the thunks target, or orphans get computed against the wrong store.\n if (orphanScope !== 'none') {\n const existingRows = (await (NodeShape as unknown as {\n select: () => {exec: (target?: IDataset) => Promise<Array<{id: string}>>};\n }).select().exec(ds)) as Array<{id: string}>;\n\n // Orphan shapes (in store, not in code) → delete (cascade cleans their owned subtree). In\n // `'ownedNamespaces'` mode, only shapes within a namespace this process writes are eligible —\n // other writers' shapes (different package namespace) are left untouched.\n for (const {id: iri} of existingRows) {\n if (localShapeIris.has(iri)) continue;\n if (orphanScope === 'ownedNamespaces' && !ownedNamespaces.has(shapeNamespace(iri))) {\n continue;\n }\n thunks.push(() =>\n (DeleteBuilder.from(NodeShape, {id: iri}).exec(ds) as Promise<unknown>).then(\n () => undefined,\n ),\n );\n }\n }\n\n return thunks;\n}\n\n/**\n * Plan an idempotent sync of ONE code-registered NodeShape into the store as SHACL data.\n *\n * Scoped counterpart to {@link syncShapes}: materializes a single shape (delete → recreate, so the\n * delete cascade-cleans the old property-shape / list / path subtrees and the create rebuilds them)\n * and does NOT run the store-wide orphan sweep — other shapes in the store are untouched.\n *\n * @param target a shape class (e.g. `Person`) or its NodeShape IRI string. An IRI is resolved to\n * its registered class via `getShapeClass`; the shape must be code-registered.\n * @param ds optional explicit dataset to materialize into (a store or a router) — both the delete\n * and the create run against it instead of the global router. Omitted → global behavior.\n * @param options `force: true` rewrites the shape even when its stored hash matches.\n * @returns a single unexecuted thunk (consistent with {@link syncShapes}), so callers can batch\n * several together — e.g. a shape plus its referenced object-property shapes:\n * `await Promise.all([syncShape(Person), syncShape(Address)].map((run) => run()))`.\n * Unless `force` is set, the thunk first reads the shape's stored `core:shapeHash` and writes\n * nothing when it equals the hash of what it would write (see {@link syncShapes}).\n * @throws if `target` is a framework/meta shape, is not registered, or has no `.shape`.\n */\nexport function syncShape(\n target: typeof Shape | string,\n ds?: IDataset,\n options?: SyncShapeOptions,\n): () => Promise<void> {\n // Normalize target → its registered shape class.\n const cls =\n typeof target === 'string' ? getShapeClass(target) : (target as typeof Shape);\n if (typeof target === 'string' && !cls) {\n throw new Error(`syncShape: no registered shape for IRI ${target}`);\n }\n const nodeShape = cls?.shape;\n if (!nodeShape) {\n throw new Error(\n typeof target === 'string'\n ? `syncShape: no registered shape for IRI ${target}`\n : `syncShape: shape class has no static .shape`,\n );\n }\n const iri = nodeShape.id;\n\n // Never materialize a framework/meta shape as user data — same invariant syncShapes() enforces\n // by skipping (the base Shape carries no packageName).\n const pkg = (cls as {packageName?: string}).packageName;\n if (!pkg || pkg === FRAMEWORK_PACKAGE) {\n throw new Error(`syncShape: refusing to sync framework/meta shape ${iri}`);\n }\n\n assertNoGeneratedIriCollision(nodeShape, iri, (id) => !!getShapeClass(id));\n if (options?.force) return buildSyncThunk(nodeShape, iri, ds);\n return async () => {\n const stored = await readStoredHashes([iri], ds);\n if (stored.get(iri) === buildSyncData(nodeShape, iri).hash) return;\n await writeShape(nodeShape, iri, ds);\n };\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  import type { IRSelectQuery, IRAskQuery, IRCountQuery, IRCreateMutation, IRUpdateMutation, IRUpsertMutation, IRDeleteMutation, IRDeleteAllMutation, IRDeleteWhereMutation, IRUpdateWhereMutation } from '../queries/IntermediateRepresentation.js';
2
- import type { PropertyShapeData } from '../shapes/nodeShapeData.js';
3
2
  import type { NodeReferenceValue } from '../utils/NodeReference.js';
4
3
  import type { SparqlSelectPlan, SparqlAskPlan, SparqlInsertDataPlan, SparqlDeleteInsertPlan, SparqlAlgebraNode, SparqlTriple, SparqlTerm } from './SparqlAlgebra.js';
5
4
  import { type SparqlOptions } from './sparqlUtils.js';
@@ -27,39 +26,19 @@ export declare function updateToAlgebra(query: IRUpdateMutation, options?: Sparq
27
26
  * needs no guard.
28
27
  */
29
28
  export declare function upsertToAlgebra(query: IRUpsertMutation, options?: SparqlOptions): SparqlDeleteInsertPlan;
30
- type Containment = {
31
- containsPreds: string[];
32
- dependentTypes: string[];
33
- /** Per dependent targetClass: the blank-capable properties of the shapes targeting it. */
34
- dependentBlankProps: Map<string, PropertyShapeData[]>;
35
- };
36
- /** Gather contains-predicate IRIs and dependent targetClass IRIs from the registry. */
37
- export declare function collectContainment(): Containment;
38
29
  /**
39
- * Build DELETE patterns + WHERE OPTIONAL blocks that cascade-delete the owned subtree
40
- * reachable from `rootTerm` via `contains` edges. `varPrefix` keeps generated variables
41
- * unique across multiple roots in one query. Returns empty when nothing is owned.
42
- *
43
- * `anchor`, when given, leads every block: the triple that binds a variable root, so
44
- * each block stays correct on its own (as a UNION branch) when no such root exists.
45
- * `onlyTypes`, when given, restricts the blocks to those dependent types (a subject delete
46
- * passes the types its shape can reach); by default every registered dependent type gets one.
30
+ * How many times one walk path may re-enter a shape it already passed through (a cycle through
31
+ * several shapes, or a sub-shape's edge back into its own kind). Values below are not deleted.
47
32
  */
48
- export declare function buildOwnedCascade(rootTerm: SparqlTerm, varPrefix: string, anchor?: SparqlTriple, keep?: SparqlTerm[], onlyTypes?: string[]): {
49
- deletePatterns: SparqlTriple[];
50
- whereOptionals: SparqlAlgebraNode[];
51
- };
33
+ export declare const MAX_OWNED_RECURSION = 4;
34
+ /** Above this many branches for one root shape, lowering warns once (see backlog 055). */
35
+ export declare const OWNED_BRANCH_WARNING = 64;
52
36
  /**
53
37
  * Build DELETE + WHERE OPTIONAL that removes the *old node's own* one-hop triples when a
54
38
  * `contains` edge is replaced, unset, or set-removed. A `contains` edge asserts exclusive
55
39
  * ownership, so overwriting it must delete the previously owned child fully — not merely
56
- * unlink it — or the child orphans (backlog 032). This is `contains`-driven and deliberately
57
- * does NOT require the child shape to be `dependent`: ownership via the edge is sufficient.
58
- * Owned descendants *below* the old node are cascaded separately by `buildOwnedCascade`.
59
- *
60
- * Callers use it only for a property that declares a value shape. A shape-less `contains`
61
- * slot (like `sh:path`) may hold a shared IRI, so its old value is left to
62
- * `buildOwnedCascade`, which deletes it only when it is dependent-typed.
40
+ * unlink it — or the child orphans (backlog 032). Ownership via the edge is sufficient.
41
+ * Owned descendants *below* the old node are deleted separately (`ownedSubtreeBlocks`).
63
42
  *
64
43
  * The owning edge `<subject> <prop> ?old` is re-asserted INSIDE the WHERE group so `?old`
65
44
  * is bound there: when no old value exists the group matches nothing and the DELETE is a
@@ -79,19 +58,18 @@ export declare function buildOwnedSelfDelete(subjectTerm: SparqlTerm, propertyTe
79
58
  * Converts an IRDeleteMutation to a SparqlDeleteInsertPlan (DELETE + WHERE).
80
59
  *
81
60
  * The WHERE is the type guard of every id, joined with ONE UNION of independent
82
- * blocks: per id its own triples, its incoming references and, for a shape that
83
- * owns something, one block per immediately-owned child (`<s> <p> ?dN . ?dN ?dN_p ?dN_o`,
84
- * for each of the shape's own and inherited `contains` properties with a value shape and
85
- * a simple path) and one block per dependent type its owned subtree can reach
86
- * (`reachableDependentTypes`; none for a shape that owns only non-dependent values). The
61
+ * blocks: per id its own triples, its incoming references, its blank values and one branch
62
+ * per owned path, plus that node's blank values (`ownedSubtreeBlocks`: the shape's own and
63
+ * inherited `contains` properties, their value shapes' in turn, and the extra ones of
64
+ * registered sub-shapes behind a type guard; none for a shape that owns nothing). The
87
65
  * bulk deletes (`deleteAllToAlgebra`, `deleteWhereToAlgebra`) add the same owned blocks,
88
66
  * rooted at the subject variable (see `bulkDeleteUnion`).
89
67
  *
90
68
  * The blocks must not be chained as OPTIONALs. A chain of OPTIONALs is a join, so
91
69
  * the solutions multiply: own triples x incoming references x owned triples of each
92
- * dependent type. Deleting one shape description with the shape sync's cascade
70
+ * owned path. Deleting one shape description with the shape sync's cascade
93
71
  * produced ~27,000 solutions for ~130 triples and took over 30 seconds on Fuseki,
94
- * which re-evaluates the cascade property path for every left-hand row. A UNION
72
+ * which re-evaluated the former registry-wide cascade path for every left-hand row. A UNION
95
73
  * yields each block's matches once, so the solutions add up instead, and it deletes
96
74
  * exactly the same triples: a DELETE template triple whose variables a solution
97
75
  * leaves unbound is skipped, as it was for an OPTIONAL that did not match.
@@ -105,7 +83,7 @@ export declare function deleteToAlgebra(query: IRDeleteMutation, _options?: Spar
105
83
  *
106
84
  * Generates DELETE { ?a0 ?p ?o . [blank-node and owned-cleanup wildcards] }
107
85
  * WHERE { ?a0 a <Shape> . { ?a0 ?p ?o } UNION [one block per blank node,
108
- * owned child and dependent type] }
86
+ * owned group] }
109
87
  * (see `bulkDeleteUnion`). Unlike a delete by id, incoming references are not deleted.
110
88
  */
111
89
  export declare function deleteAllToAlgebra(query: IRDeleteAllMutation, _options?: SparqlOptions): SparqlDeleteInsertPlan;
@@ -113,7 +91,7 @@ export declare function deleteAllToAlgebra(query: IRDeleteAllMutation, _options?
113
91
  * Converts an IRDeleteWhereMutation to a SparqlDeleteInsertPlan.
114
92
  *
115
93
  * Like deleteAllToAlgebra but adds filter conditions from the where clause. The cleanup
116
- * UNION (blank nodes, owned children, dependent cascade) is joined with the filtered match,
94
+ * UNION (blank nodes, owned subtree) is joined with the filtered match,
117
95
  * so only the matched subjects' children are deleted.
118
96
  */
119
97
  export declare function deleteWhereToAlgebra(query: IRDeleteWhereMutation, _options?: SparqlOptions): SparqlDeleteInsertPlan;
@@ -209,4 +187,3 @@ export declare function deleteWhereToSparql(query: IRDeleteWhereMutation, option
209
187
  * Converts an IRUpdateWhereMutation to a SPARQL string.
210
188
  */
211
189
  export declare function updateWhereToSparql(query: IRUpdateWhereMutation, options?: SparqlOptions): string;
212
- export {};