@ghentcdh/annotation-api 0.0.1-alpha.10 → 0.0.1-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1 +1,856 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@nestjs/common"),t=require("zod"),n=require("@ghentcdh/w3c-utils"),r=require("@ghentcdh/annotated-text"),i=require("@ghentcdh/crouton-forms-vue"),a=require("node:fs"),o=require("node:path"),s=require("@nestjs/swagger");var c=[`text`],l=t.z.object({text:t.z.string(),textDirection:t.z.enum([`ltr`,`rtl`]).default(`ltr`),processingLanguage:t.z.string().default(`en`),label:t.z.string().optional(),offset:t.z.number().optional().default(0)}),u=t.z.object({id:t.z.string(),uri:t.z.string(),type:t.z.enum(c),content:l}),d=e=>{let t=e.areas.map(e=>`"${e.join(` `)}"`).join(` `),n=e.areas[0]?.length??1,r={gridTemplateAreas:t,gridTemplateColumns:e.columns??Array(n).fill(`minmax(0, 1fr)`).join(` `)};return e.rows&&(r.gridTemplateRows=e.rows),r},f=(e,t)=>e.panes.find(e=>e.sourceId===t)?.area,p=`AnnotationMetadata`,m=t.z.custom(),h=t.z.object({id:t.z.string(),name:t.z.string(),columns:t.z.array(m),json_schema:t.z.any().optional(),json_ld:t.z.any().optional(),ui_schema:t.z.any().optional(),metadata_schema:t.z.any().optional(),color:t.z.string(),type:t.z.string().optional(),icon:t.z.string().optional(),isRoot:t.z.boolean().default(!0),allowedChildren:t.z.array(t.z.string()).default([]),allowedLinks:t.z.array(t.z.string()).default([]),context:t.z.custom(),target:t.z.enum([`gutter`,`underline`,`highlight`]).default(`highlight`)}),g={baseUrl:`http://localhost:3000/`,app:`ghentcdh`,prefix:`ghentcdh`,isDev:!1,cacheTTLms:1200*1e3},_=(e={})=>{let t=e.baseUrl??g.baseUrl,n=t.endsWith(`/`)?t:`${t}/`,r=e.isDev??!1,i=r?0:1200*1e3;return{baseUrl:n,contextUrl:`${n}ns/`,app:e.app??g.app,prefix:e.prefix??g.prefix,isDev:r,cacheTTLms:i}},v=(e,t)=>{let{prefix:r,baseUrl:i,contextUrl:a}=_(t),o=p;return(0,n.contextBuilder)(r,i).setType(r,o).addPrefix(e,`${r}:${e}`).setContextUri(`${a}${e}.jsonld`)},y=`annotation.style`,b=t.z.object({id:t.z.string(),name:t.z.string(),target:t.z.enum([`gutter`,`underline`,`highlight`]).optional().default(`underline`),color:t.z.string().optional()}),x=`AnnotationStyle`,S=e=>{let{prefix:t,baseUrl:r,contextUrl:i}=_(e);return(0,n.contextBuilder)(t,r).setType(t,x).setContextUri(`${i}${x}.jsonld`).parseZodSchema(b)},C=(e,t)=>{let n=S(e).toAnnotationBodyUnsafe(t);return n.success||(r.Debugger.debug(y,`AnnotationStyleContextBuilder safe parse failed`),r.Debugger.warn(n.error)),n},w=e=>{let t=i.ControlBuilder.properties(e.id);if(t.customLabel(e.label),!e.fieldInput)return t;let{type:n,options:r={}}=e.fieldInput;return n===`autocomplete`?t.autocomplete({...r.uri&&{uri:r.uri},...r.resource&&{resource:r.resource},...r.valueKey&&{valueKey:r.valueKey},...r.labelKey&&{labelKey:r.labelKey},...r.enableCreate!==void 0&&{enableCreate:r.enableCreate},...r.colspan&&{colspan:r.colspan}}):n===`select`?t.select({...r.values&&{values:r.values},...r.clearable!==void 0&&{clearable:r.clearable},...r.storeValue!==void 0&&{storeValue:r.storeValue},...r.emitObject!==void 0&&{emitObject:r.emitObject},...r.colspan&&{colspan:r.colspan}}):t.control(n,{...r.colspan&&{colspan:r.colspan}})},T=e=>{let t=i.LayoutBuilder.grid();return e.filter(e=>!e.hiddenInForm).forEach(e=>t.addControl(w(e))),t.build()},E=e=>{let t=i.LayoutBuilder.grid();return e.filter(e=>!e.hiddenInMetadata).forEach(e=>t.addControl(w(e).readonly())),t.build()},D=e=>{if(e.type===`object`&&e.properties){let n={};for(let[t,r]of Object.entries(e.properties))n[t]=D(r);return t.z.object(n)}return t.z.string()},O=(e,n,r)=>{let i=v(e,r),a=n.columns??[];if(!a.length)return i;let o={};for(let e of a){let t=D(e.type??{type:`string`});o[e.id]=e.required===!1?t.optional():t}return Object.keys(o).length?i.parseZodSchema(t.z.object(o)):i},k=(e,t,n=O)=>{let r=n(e.id,e,t),i=e.columns??[],a=i.length>0,o=e.ui_schema??(a?T(i):void 0),s=e.metadata_schema??(a?E(i):void 0),c={id:e.id,name:e.name,color:e.color,isRoot:e.isRoot??!0,columns:i,context:r,json_ld:r.toJsonLdContext(),json_schema:o?r.toJsonSchema():null,allowedChildren:e.allowedChildren??[],allowedLinks:e.allowedLinks??[],target:e.target??`highlight`};return o&&(c.ui_schema=o),s&&(c.metadata_schema=s),e.type&&(c.type=e.type),e.icon&&(c.icon=e.icon),c},ee=(e,t,n)=>e.map(e=>k(e,t,n)),te=(e,t,n)=>n.map(r=>{let i=t.get(r.id),a=i.getSpecificResourceTargets(e);if(!a||a.length===0)return null;let o=i.getSpecificResourceTargets().map(e=>e.source).filter(t=>t!==e).map(e=>n.find(t=>t.id===e)).filter(Boolean);return{purpose:A(i),annotation:r,relations:o}}).filter(Boolean),A=e=>j(e)?.id??`text`,j=e=>e.getBodiesByPurpose(`styling`).find(e=>e.type===`AnnotationStyle`),M=(e,t,n)=>{let r=t.getSpecificResourceTargets()[0]?.source;if(!r)return null;let i=t.getTextPositionSelector(r)[0];if(!i)return null;let a=j(t)?.id??`text`;return{id:e,start:i.start,end:i.end,allowedChildren:n[a]??[],sourceUri:r??``,type:a,minX:i.start,minY:0,maxX:i.end,maxY:0}},N=`ROOT`,P=()=>`mela:new-annotation:${Date.now()}`,F=(e,t)=>(e.getSpecificResourceTargets(t.source).length||e.addTarget({type:`SpecificResource`,source:t.source}),e.updateTextPositionSelector({start:t.start,end:t.end},t.source),e),I=class{annotationConfig;builderMap=new Map;childParentMap=new Map;parentChildMap=new Map;linkedAnnotations=new Map;annotations=[];allowedChildrenPerType={};constructor(e){this.annotationConfig=e}getBuilder(e){let t=this.builderMap.get(e.id);if(!t)throw Error(`Annotation builder not found: ${e.id}`);return t}setAnnotations(e,t){this.allowedChildrenPerType=t,this.annotations=e,this.parentChildMap.clear(),this.childParentMap.clear(),this.builderMap.clear();let r=[],i=new Map;return e.forEach(e=>{let t=(0,n.w3cAnnotation)(e);this.builderMap.set(e.id,t);let a=M(e.id,t,this.allowedChildrenPerType);i.set(e.id,e),a&&r.push(a)}),r.forEach(e=>{let t=r.filter(t=>t.id!==e.id&&t.sourceUri===e.sourceUri&&t.start<=e.start&&t.end>=e.end&&t.allowedChildren.some(t=>t.key===e.type)).sort((e,t)=>e.end-e.start-(t.end-t.start))[0],n=t?.id??N,a=this.parentChildMap.get(n)??[];a.push(i.get(e.id)),this.parentChildMap.set(t?.id??N,a),this.childParentMap.set(e.id,i.get(n)??null)}),e.forEach(t=>{this.linkedAnnotations.set(t.id,te(t.id,this.builderMap,e))}),this}getLinks(e){return this.linkedAnnotations.get(e.id)??[]}getTextPositionSelector(e,t){return this.getBuilder(e).getTextPositionSelector(t)[0]}isAnnotationUri=e=>e.startsWith(`mela:annotation/`);getParentSelector=e=>e.getSpecificResourceTargets().find(e=>this.isAnnotationUri(e.source))??null;getParent(e){let t=this.getBuilder(e),n=this.getParentSelector(t);return n?this.annotations.find(e=>e.id===n.source)??null:null}createAnnotation(e,t,r,i){let a=S(this.annotationConfig).toAnnotationBody(t),o=(0,n.w3cAnnotation)(e??void 0).setMotivation(`tagging`).addBody(a);return e?.id||o.setId(P()),r&&Object.keys(r).length>0&&(r.type=r.type??`AnnotationMetadata`,r.purpose=r.purpose??A(o),o.updateBodyByType(r.type,r)),i&&F(o,i),o.build()}createLinkAnnotation=(e,t,r,i)=>{let a=S(this.annotationConfig).toAnnotationBody(r),o=(0,n.w3cAnnotation)().setMotivation(`tagging`).setId(P()).addBody(a);return i&&Object.keys(i).length>0&&(i.type=i.type??`AnnotationMetadata`,i.purpose=i.purpose??A(o),o.updateBodyByType(i.type,i)),o.addTarget({source:e.id}).addTarget({source:t.id}),o.build()};cancel(){this.setAnnotations(this.annotations,this.allowedChildrenPerType)}getSourceUri=e=>{let t=this.getBuilder(e),n=t.getSourceUri();return n?{textPositionSelector:t.getTextPositionSelector(n)[0],sourceUri:n}:(console.warn(`no source uri`),null)};getMetadata=(e,t)=>this.getBuilder(e).getBodiesByType(`AnnotationMetadata`)?.[0]??null;getAnnotationStyle=e=>j(this.getBuilder(e));getAnnotationType=e=>A(this.getBuilder(e));createAnnotationFromSelector(e,t,r){let i=(0,n.w3cAnnotation)(t??void 0).setMotivation(`tagging`).setId(P()),a=S(this.annotationConfig).toAnnotationBody(e);return i.addBody(a),r&&F(i,r),i.build()}},L=e=>new I(e),R=e=>t=>e?.getAnnotationStyle(t)?.target??`default`,z=(e,t)=>n=>{let i=t?.getAnnotationStyle(n);if(!i)return`default`;let a=i?.id??`default`;return e.includes(a)?a:(r.Debugger.debug(`styleFn`,`No style found for ${a}`),i.color?{default:(0,r.createHighlightStyle)(i.color)}:`default`)},B=(e,t)=>e?e.reduce((e,n)=>(e[n.id]=t?n[t]:n,e),{}):{},V=(e,t,n,i)=>{let a=e??[],o=B(a),s=a.filter(e=>e.isRoot).map(e=>({key:e.id,label:e.label})),c=B(a,`style`);c.default||={label:`Annotation`,isRoot:!0,style:{default:(0,r.createHighlightStyle)(`#dd7777`)},allowedChildren:[],allowedLinks:[],schema:{uiSchema:{type:`VerticalLayout`,elements:[]},jsonSchema:{type:`object`,properties:{}},metaDataSchema:{type:`VerticalLayout`,elements:[]},validation:()=>void 0}};let l=Object.keys(c),u=B(a,`allowedChildren`),d=e=>(0,r.W3CAnnotationAdapter)(e?{sourceUri:e.uri}:{}),f=()=>({renderFn:R(t)}),p=()=>({styleFn:z(l,t)});return{allowedChildrenPerType:u,definitions:a,getDefinition:e=>o[e]??void 0,rootTypes:s,createAnnotatedText:(e,t)=>{let a=(0,r.createAnnotatedText)(e);if(a.setSnapper(new r.WordSnapper).setAnnotationAdapter(i??d(t)).setTextAdapter(n??(0,r.PlainTextAdapter)()).setRenderParams(f()).setStyleParams(p()).registerStyles(c),t){let{content:e}=t;a.setText(e.text).setTextAdapter({textDirection:e.textDirection})}return a}}},H=Symbol(`ANNOTATION_DEF_CONFIG_TOKEN`);function U(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function W(e,t){return function(n,r){t(n,r,e)}}function G(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var K=class{config;definitions=[];groupedDefinitions={};cachedAt=0;constructor(e){this.config=e}async findAllGrouped(){return await this.setDefinitions(),Promise.resolve(this.groupedDefinitions)}async setDefinitions(e=!1){let t=Date.now();if(!e&&this.definitions.length&&t-this.cachedAt<this.config.cacheTTLms)return;let n=await this.reloadDefinitions()??[];this.definitions=n,this.groupedDefinitions=n.reduce((e,t)=>(e[t.id]=t,e),{}),this.cachedAt=t}async findAll(){return await this.setDefinitions(),Promise.resolve(this.definitions)}async findById(t){await this.setDefinitions();let n=this.groupedDefinitions[t];if(n||await this.setDefinitions(!0),n=this.groupedDefinitions[t],!n)throw new e.NotFoundException;return Promise.resolve(n)}async getAllContextBuilders(){return(await this.findAll()).map(e=>e.context)}async getContextBuilder(t){let n=await this.findById(t);if(!n)throw new e.NotFoundException;return n.context}};K=G([(0,e.Injectable)(),W(0,(0,e.Inject)(H)),U(`design:paramtypes`,[Object])],K);var q=class extends K{_initialDefinitions;_loaderFn;constructor(e,t,n){super(e),this._initialDefinitions=t,this._loaderFn=n}reloadDefinitions=()=>this.config.isDev&&this._loaderFn?Promise.resolve(this._loaderFn()):Promise.resolve(this._initialDefinitions??[])};q=G([(0,e.Injectable)(),W(0,(0,e.Inject)(H)),U(`design:paramtypes`,[Object,Array,Object])],q);var J=(e,t,n)=>{if(!(0,a.existsSync)(e))return[];let r=(0,a.readdirSync)(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name),i=[];for(let s of r){let r=(0,o.join)(e,s,`resource.json`);if(!(0,a.existsSync)(r))continue;let c=JSON.parse((0,a.readFileSync)(r,`utf-8`));i.push(k(c,t,n))}return i},Y=class{service;annotationDefConfig;constructor(e,t){this.service=e,this.annotationDefConfig=t}getAll(){return this.service.findAll()}async getJsonLd_(e){return e===`AnnotationStyle`?S(this.annotationDefConfig).toJsonLdContext():(await this.service.findById(e))?.json_ld}async getSchemas(e){let t=await this.service.findById(e);return{id:t.id,name:t.name,json_schema:t.json_schema,ui_schema:t.ui_schema,metadata_schema:t.metadata_schema,columns:t.columns,isRoot:t.isRoot,allowedChildren:t.allowedChildren,allowedLinks:t.allowedLinks,type:t.type,icon:t.icon,target:t.target}}async getById(e){return await this.service.findById(e)}async getFullJsonLd(){return(await this.service.getAllContextBuilders()).map(e=>e.toJsonLdContext())}async getJsonLd(e){let t=await this.service.getContextBuilder(e);return{jsonLd:t.toJsonLdContext(),forms:t.toJsonSchema()}}};G([(0,e.Get)(),U(`design:type`,Function),U(`design:paramtypes`,[]),U(`design:returntype`,void 0)],Y.prototype,`getAll`,null),G([(0,e.Get)(`:id.jsonld`),W(0,(0,e.Param)(`id`)),U(`design:type`,Function),U(`design:paramtypes`,[String]),U(`design:returntype`,Promise)],Y.prototype,`getJsonLd_`,null),G([(0,e.Get)(`:id/schemas`),W(0,(0,e.Param)(`id`)),U(`design:type`,Function),U(`design:paramtypes`,[String]),U(`design:returntype`,Promise)],Y.prototype,`getSchemas`,null),G([(0,e.Get)(`:id`),W(0,(0,e.Param)(`id`)),U(`design:type`,Function),U(`design:paramtypes`,[String]),U(`design:returntype`,Promise)],Y.prototype,`getById`,null),G([(0,e.Get)(`anno.jsonld`),U(`design:type`,Function),U(`design:paramtypes`,[]),U(`design:returntype`,Promise)],Y.prototype,`getFullJsonLd`,null),G([(0,e.Get)(`:type/anno.jsonld`),W(0,(0,e.Param)(`type`)),U(`design:type`,Function),U(`design:paramtypes`,[String]),U(`design:returntype`,Promise)],Y.prototype,`getJsonLd`,null),Y=G([(0,e.Controller)(`ns`),(0,s.ApiTags)(`Annotations NS`),W(0,(0,e.Inject)(K)),W(1,(0,e.Inject)(H)),U(`design:paramtypes`,[K===void 0?Object:K,Object])],Y);var X=(e,t)=>{let n=(0,o.join)(e,`_resource`);if(!(0,a.existsSync)(n))return[];let r=(0,a.readdirSync)(n).filter(e=>e.endsWith(`.json`)),{prefix:i}=_(t);return r.map(e=>{let t=JSON.parse((0,a.readFileSync)((0,o.join)(n,e),`utf-8`)),r=t.columns.find(e=>e.displayAs===`id`),s=t.columns.find(e=>e.displayAs===`label`);return{type:t.type,table:t.table,database:t.database,field:{id:r?.column??`id`,label:s?.column??`name`},prefix:`${i}:${t.type}/`}})},Z=class{byType=new Map;constructor(e){for(let t of e)this.byType.set(t.type,t)}findAll=()=>[...this.byType.values()];getResourceForType=e=>this.byType.get(e)??null;getResourceFromUri=e=>{for(let t of this.byType.values())if(e.startsWith(t.prefix))return{...t,id:e.substring(t.prefix.length)};return null}};Z=G([(0,e.Injectable)(),U(`design:paramtypes`,[Array])],Z);var Q,$=Q=class{static forService(e){return{module:Q,global:!0,controllers:[Y],providers:[{provide:K,useClass:e.annotationDefinitionService}],exports:[K]}}static async forResourceDir(e,t){let n=()=>J(e,t,O),r=new q(t,n(),n),i=new Z(X(e,t));return{module:Q,global:!0,controllers:[Y],providers:[{provide:H,useValue:t},{provide:K,useValue:r},{provide:Z,useValue:i}],exports:[K,Z]}}};$=Q=G([(0,e.Module)({controllers:[],providers:[],exports:[]})],$),exports.ANNOTATION_DEF_CONFIG_TOKEN=H,Object.defineProperty(exports,"AnnotationApiModule",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"AnnotationDefinitionFromFilesService",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"AnnotationDefinitionService",{enumerable:!0,get:function(){return K}}),exports.AnnotationMetadataType=p,Object.defineProperty(exports,"AnnotationResourceDefinitionService",{enumerable:!0,get:function(){return Z}}),exports.AnnotationStyleContextBuilder=S,exports.AnnotationStyleType=x,exports.SourceModelSchema=u,exports.SourceTextSchema=l,exports.annotationColumnDefinition=m,exports.annotationContextBuilderFactory=O,exports.annotationDefinition=h,exports.annotationUtils=L,exports.baseContextBuilder=v,exports.buildAnnotationDefinition=k,exports.buildAnnotationDefinitions=ee,exports.buildGridStyle=d,exports.buildMetadataSchema=E,exports.buildUiSchema=T,exports.createAnnotationConfiguration=V,exports.createAnnotationStyleBodyUnsafe=C,exports.defaultRender=R,exports.getPaneArea=f,exports.jsonSchemaPropertyToZod=D,exports.loadAnnotationDefinitionsFromDir=J,exports.loadAnnotationResourcesFromDir=X,exports.resolveConfig=_,exports.styleFn=z;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _nestjs_common = require("@nestjs/common");
3
+ let zod = require("zod");
4
+ let _ghentcdh_w3c_utils = require("@ghentcdh/w3c-utils");
5
+ let _ghentcdh_crouton_core = require("@ghentcdh/crouton-core");
6
+ let _ghentcdh_annotated_text = require("@ghentcdh/annotated-text");
7
+ let _ghentcdh_crouton_api = require("@ghentcdh/crouton-api");
8
+ let _nestjs_swagger = require("@nestjs/swagger");
9
+ //#region src/lib/annotation/annotation.repository.ts
10
+ var AnnotationCrudRepository = class {};
11
+ //#endregion
12
+ //#region ../annotation-core/src/lib/types/key-label.type.ts
13
+ var KeyLabelSchema = zod.z.object();
14
+ //#endregion
15
+ //#region ../annotation-core/src/lib/types/source.model.ts
16
+ var SourceTypesList = ["text"];
17
+ var SourceTextSchema = zod.z.object({
18
+ text: zod.z.string(),
19
+ textDirection: zod.z.enum(["ltr", "rtl"]).default("ltr"),
20
+ processingLanguage: zod.z.string().default("en"),
21
+ label: zod.z.string().optional(),
22
+ offset: zod.z.number().optional().default(0)
23
+ });
24
+ var SourceModelSchema = zod.z.object({
25
+ id: zod.z.string(),
26
+ uri: zod.z.string(),
27
+ type: zod.z.enum(SourceTypesList),
28
+ content: SourceTextSchema
29
+ });
30
+ //#endregion
31
+ //#region ../annotation-core/src/lib/types/grid-layout.types.ts
32
+ /** Computed CSS styles for the grid container */
33
+ var buildGridStyle = (layout) => {
34
+ const templateAreas = layout.areas.map((row) => `"${row.join(" ")}"`).join(" ");
35
+ const colCount = layout.areas[0]?.length ?? 1;
36
+ const style = {
37
+ gridTemplateAreas: templateAreas,
38
+ gridTemplateColumns: layout.columns ?? Array(colCount).fill("minmax(0, 1fr)").join(" ")
39
+ };
40
+ if (layout.rows) style["gridTemplateRows"] = layout.rows;
41
+ return style;
42
+ };
43
+ /** Returns the grid-area CSS value for a given source id, or undefined if not configured */
44
+ var getPaneArea = (layout, sourceId) => {
45
+ return layout.panes.find((p) => p.sourceId === sourceId)?.area;
46
+ };
47
+ //#endregion
48
+ //#region ../annotation-core/src/lib/utils/annotation.context-builder.ts
49
+ var defaultConfig = {
50
+ baseUrl: "http://localhost:3333/",
51
+ crudController: "annotation/annotation",
52
+ app: "ghentcdh",
53
+ prefix: "ghentcdh",
54
+ isDev: false,
55
+ cacheTTLms: 1200 * 1e3
56
+ };
57
+ var resolveConfig = (config = {}) => {
58
+ const baseUrl = config.baseUrl ?? defaultConfig.baseUrl;
59
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
60
+ const isDev = config.isDev ?? false;
61
+ const cacheTTLms = isDev ? 0 : 1200 * 1e3;
62
+ return {
63
+ baseUrl: normalizedBaseUrl,
64
+ contextUrl: `${normalizedBaseUrl}ns/`,
65
+ app: config.app ?? defaultConfig.app,
66
+ prefix: config.prefix ?? defaultConfig.prefix,
67
+ crudController: config.crudController ?? defaultConfig.crudController,
68
+ isDev,
69
+ cacheTTLms
70
+ };
71
+ };
72
+ var baseContextBuilder = (id, config) => {
73
+ const { prefix, baseUrl, contextUrl } = resolveConfig(config);
74
+ const metaData = AnnotationMetadataType;
75
+ return (0, _ghentcdh_w3c_utils.contextBuilder)(prefix, baseUrl).setType(prefix, metaData).addPrefix(id, `${prefix}:${id}`).setContextUri(`${contextUrl}${id}.jsonld`);
76
+ };
77
+ //#endregion
78
+ //#region ../annotation-core/src/lib/types/annotation.contex.ts
79
+ var AnnotationMetadataType = "AnnotationMetadata";
80
+ var createAnnotationContext = (annotationDefConfig, resource) => {
81
+ const formView = resource.views?.["form"];
82
+ const builder = baseContextBuilder(resource.id, annotationDefConfig);
83
+ if (formView) builder.parseJsonSchema(formView.json_schema);
84
+ return {
85
+ id: resource.id,
86
+ styling: {
87
+ name: resource.name,
88
+ id: resource.id,
89
+ target: resource.annotation.target,
90
+ color: resource.annotation.color
91
+ },
92
+ hasContext: !!formView,
93
+ prefix: buildPrefix(annotationDefConfig, resource),
94
+ uri: builder.uri,
95
+ jsonLd: builder.toJsonLdContext(),
96
+ safeParse: builder.safeParse.bind(builder),
97
+ toAnnotationBody: builder.toAnnotationBody.bind(builder)
98
+ };
99
+ };
100
+ var buildPrefix = (annotationDefConfig, resource) => {
101
+ return `${annotationDefConfig.prefix}:${resource.annotation.type}/`;
102
+ };
103
+ //#endregion
104
+ //#region ../annotation-core/src/lib/types/version.ts
105
+ /**
106
+ * resource.json schema versioning.
107
+ *
108
+ * `schemaVersion` is a monotonic integer stamped on every `resource.json`. It is
109
+ * **decoupled from the crouton package semver** on purpose — bump it only when the
110
+ * resource.json *shape* changes in a way that needs a migration, and ship a matching
111
+ * step in `./migrations`. This keeps the migration chain one-step-per-bump with no
112
+ * version-range math.
113
+ *
114
+ * Files written before versioning existed carry no field and are treated as the
115
+ * baseline. Because `CURRENT_RESOURCE_VERSION` starts equal to the baseline, shipping
116
+ * the versioning machinery is a pure no-op for every existing file until the first
117
+ * real shape change lands (`CURRENT_RESOURCE_VERSION = 2` + a `1 → 2` migration).
118
+ */
119
+ /** Version assumed for a `resource.json` that has no `schemaVersion` field. */
120
+ var BASELINE_RESOURCE_VERSION = 1;
121
+ /**
122
+ * The version the running crouton understands. Bump by 1 whenever resource.json's
123
+ * shape changes, and add a migration step (`from: N, to: N + 1`) in `./migrations`.
124
+ */
125
+ var CURRENT_RESOURCE_VERSION = 1;
126
+ //#endregion
127
+ //#region ../annotation-core/src/lib/types/annotation-json-config.types.ts
128
+ var AnnotationTargetEnum = zod.z.enum([
129
+ "gutter",
130
+ "underline",
131
+ "highlight"
132
+ ]);
133
+ var AnnotationConfigSchema = zod.z.object({
134
+ color: zod.z.string().optional(),
135
+ type: zod.z.string().optional(),
136
+ icon: zod.z.string().optional(),
137
+ isRoot: zod.z.boolean().optional().default(true),
138
+ allowedChildren: zod.z.array(zod.z.string()).optional().default([]),
139
+ allowedLinks: zod.z.array(zod.z.string()).optional().default([]),
140
+ target: AnnotationTargetEnum.optional().default("highlight")
141
+ });
142
+ var AnnotationJsonResourceShape = _ghentcdh_crouton_core.ResourceJsonShape.extend({
143
+ route: zod.z.string().optional(),
144
+ tag: zod.z.string().optional(),
145
+ operations: _ghentcdh_crouton_core.JsonOperationsSchema.optional().default(_ghentcdh_crouton_core.JsonOperationsSchema.parse({})),
146
+ id: zod.z.string(),
147
+ annotation: AnnotationConfigSchema.optional().default(AnnotationConfigSchema.parse({}))
148
+ }).passthrough();
149
+ var AnnotationJsonResourceSchema = AnnotationJsonResourceShape.transform((obj) => {
150
+ const title = (0, _ghentcdh_crouton_core.labelFromId)(obj.name);
151
+ return {
152
+ schemaVersion: obj.schemaVersion ?? 1,
153
+ title,
154
+ ...obj
155
+ };
156
+ });
157
+ //#endregion
158
+ //#region ../annotation-core/src/lib/types/annotation-definition.type.ts
159
+ var annotationColumnDefinition = zod.z.custom();
160
+ var AnnotationResourceSchema = AnnotationJsonResourceShape.pick({
161
+ id: true,
162
+ name: true,
163
+ title: true,
164
+ operations: true,
165
+ annotation: true
166
+ }).extend({
167
+ annotation: AnnotationConfigSchema,
168
+ context: zod.z.instanceof(_ghentcdh_w3c_utils.ContextBuilder).optional().nullish(),
169
+ schemas: zod.z.record(zod.z.string(), _ghentcdh_crouton_core.ViewConfigSchema.partial()).optional().nullish()
170
+ });
171
+ //#endregion
172
+ //#region ../annotation-core/src/lib/annotation.style.ts
173
+ var CONTEXT = "annotation.style";
174
+ var AnnotationStyleSchema = zod.z.object({
175
+ id: zod.z.string(),
176
+ name: zod.z.string(),
177
+ target: zod.z.enum([
178
+ "gutter",
179
+ "underline",
180
+ "highlight"
181
+ ]).optional().default("underline"),
182
+ color: zod.z.string().optional()
183
+ });
184
+ var AnnotationStyleType = "AnnotationStyle";
185
+ var AnnotationStyleContextBuilder = (annotationConfig) => {
186
+ const { prefix, baseUrl, contextUrl } = resolveConfig(annotationConfig);
187
+ return (0, _ghentcdh_w3c_utils.contextBuilder)(prefix, baseUrl).setType(prefix, AnnotationStyleType).setContextUri(`${contextUrl}${AnnotationStyleType}.jsonld`).parseZodSchema(AnnotationStyleSchema);
188
+ };
189
+ var createAnnotationStyleBodyUnsafe = (annotationConfig, style) => {
190
+ const resource = {
191
+ ...style,
192
+ ...style.annotation
193
+ };
194
+ const parsed = AnnotationStyleContextBuilder(annotationConfig).toAnnotationBodyUnsafe(resource);
195
+ if (!parsed.success) {
196
+ _ghentcdh_annotated_text.Debugger.debug(CONTEXT, "AnnotationStyleContextBuilder safe parse failed");
197
+ _ghentcdh_annotated_text.Debugger.warn(parsed.error);
198
+ }
199
+ return parsed;
200
+ };
201
+ //#endregion
202
+ //#region ../annotation-core/src/lib/utils/annotation-utils.ts
203
+ var mapRelationsToLinks = (sourceUri, builders, annotations) => {
204
+ return annotations.map((link) => {
205
+ const builder = builders.get(link.id);
206
+ const specifyResource = builder.getSpecificResourceTargets(sourceUri);
207
+ if (!specifyResource || specifyResource.length === 0) return null;
208
+ const relations = builder.getSpecificResourceTargets().map((s) => s.source).filter((s) => s !== sourceUri).map((uri) => {
209
+ return annotations.find((a) => a.id === uri);
210
+ }).filter(Boolean);
211
+ return {
212
+ purpose: getAnnotationType(builder),
213
+ annotation: link,
214
+ relations
215
+ };
216
+ }).filter(Boolean);
217
+ };
218
+ var getAnnotationType = (builder) => {
219
+ return getAnnotationStyle(builder)?.id ?? "text";
220
+ };
221
+ var getAnnotationStyle = (builder) => {
222
+ return builder.getBodiesByPurpose("styling").find((b) => b.type === "AnnotationStyle");
223
+ };
224
+ var getAnnotationPosition = (id, builder, allowedChildrenPerType) => {
225
+ const sourceUri = builder.getSpecificResourceTargets()[0]?.source;
226
+ if (!sourceUri) return null;
227
+ const textPositionSelector = builder.getTextPositionSelector(sourceUri)[0];
228
+ if (!textPositionSelector) return null;
229
+ const type = getAnnotationStyle(builder)?.id ?? "text";
230
+ return {
231
+ id,
232
+ start: textPositionSelector.start,
233
+ end: textPositionSelector.end,
234
+ allowedChildren: allowedChildrenPerType[type] ?? [],
235
+ sourceUri: sourceUri ?? "",
236
+ type,
237
+ minX: textPositionSelector.start,
238
+ minY: 0,
239
+ maxX: textPositionSelector.end,
240
+ maxY: 0
241
+ };
242
+ };
243
+ var rootId = "ROOT";
244
+ var createId = () => {
245
+ return `mela:new-annotation:${Date.now()}`;
246
+ };
247
+ var updateSelector = (builder, selector) => {
248
+ if (!builder.getSpecificResourceTargets(selector.source).length) builder.addTarget({
249
+ type: "SpecificResource",
250
+ source: selector.source
251
+ });
252
+ builder.updateTextPositionSelector({
253
+ start: selector.start,
254
+ end: selector.end
255
+ }, selector.source);
256
+ builder.updateTextQuoteSelector({
257
+ prefix: selector.prefix,
258
+ suffix: selector.suffix,
259
+ exact: selector.exact
260
+ }, selector.source);
261
+ return builder;
262
+ };
263
+ var AnnotationUtilsImpl = class {
264
+ annotationConfig;
265
+ builderMap = /* @__PURE__ */ new Map();
266
+ childParentMap = /* @__PURE__ */ new Map();
267
+ parentChildMap = /* @__PURE__ */ new Map();
268
+ linkedAnnotations = /* @__PURE__ */ new Map();
269
+ annotations = [];
270
+ allowedChildrenPerType = {};
271
+ constructor(annotationConfig) {
272
+ this.annotationConfig = annotationConfig;
273
+ }
274
+ getBuilder(annotation) {
275
+ const builder = this.builderMap.get(annotation.id);
276
+ if (!builder) throw new Error(`Annotation builder not found: ${annotation.id}`);
277
+ return builder;
278
+ }
279
+ setAnnotations(annotations, allowedChildrenPerType) {
280
+ this.allowedChildrenPerType = allowedChildrenPerType;
281
+ this.annotations = annotations;
282
+ this.parentChildMap.clear();
283
+ this.childParentMap.clear();
284
+ this.builderMap.clear();
285
+ const annotationsWithPositons = [];
286
+ const annotationIdMap = /* @__PURE__ */ new Map();
287
+ annotations.forEach((annotation) => {
288
+ const builder = (0, _ghentcdh_w3c_utils.w3cAnnotation)(annotation);
289
+ this.builderMap.set(annotation.id, builder);
290
+ const position = getAnnotationPosition(annotation.id, builder, this.allowedChildrenPerType);
291
+ annotationIdMap.set(annotation.id, annotation);
292
+ if (position) annotationsWithPositons.push(position);
293
+ });
294
+ annotationsWithPositons.forEach((annotation) => {
295
+ const parentAnnotation = annotationsWithPositons.filter((a) => a.id !== annotation.id && a.sourceUri === annotation.sourceUri && a.start <= annotation.start && a.end >= annotation.end && a.allowedChildren.some((c) => c.key === annotation.type)).sort((a, b) => a.end - a.start - (b.end - b.start))[0];
296
+ const parentId = parentAnnotation?.id ?? rootId;
297
+ const children = this.parentChildMap.get(parentId) ?? [];
298
+ children.push(annotationIdMap.get(annotation.id));
299
+ this.parentChildMap.set(parentAnnotation?.id ?? rootId, children);
300
+ this.childParentMap.set(annotation.id, annotationIdMap.get(parentId) ?? null);
301
+ });
302
+ annotations.forEach((annotation) => {
303
+ this.linkedAnnotations.set(annotation.id, mapRelationsToLinks(annotation.id, this.builderMap, annotations));
304
+ });
305
+ return this;
306
+ }
307
+ getLinks(annotation) {
308
+ return this.linkedAnnotations.get(annotation.id) ?? [];
309
+ }
310
+ getTextPositionSelector(annotation, sourceUri) {
311
+ return this.getBuilder(annotation).getTextPositionSelector(sourceUri)[0];
312
+ }
313
+ isAnnotationUri = (uri) => {
314
+ return uri.startsWith("mela:annotation/");
315
+ };
316
+ getParentSelector = (builder) => {
317
+ return builder.getSpecificResourceTargets().find((t) => this.isAnnotationUri(t.source)) ?? null;
318
+ };
319
+ getParent(annotation) {
320
+ const builder = this.getBuilder(annotation);
321
+ const parentUri = this.getParentSelector(builder);
322
+ if (!parentUri) return null;
323
+ return this.annotations.find((a) => a.id === parentUri.source) ?? null;
324
+ }
325
+ createAnnotation(fromAnnotation, type, data, selectors) {
326
+ const styleBody = AnnotationStyleContextBuilder(this.annotationConfig).toAnnotationBody(type);
327
+ const builder = (0, _ghentcdh_w3c_utils.w3cAnnotation)(fromAnnotation ?? void 0).setMotivation("tagging").addBody(styleBody);
328
+ if (!fromAnnotation?.id) builder.setId(createId());
329
+ if (data && Object.keys(data).length > 0) {
330
+ data.type = data.type ?? "AnnotationMetadata";
331
+ data.purpose = data.purpose ?? getAnnotationType(builder);
332
+ builder.updateBodyByType(data.type, data);
333
+ }
334
+ for (const selector of selectors) updateSelector(builder, selector);
335
+ return builder.build();
336
+ }
337
+ createLinkAnnotation = (sourceAnnotation, targetAnnotation, type, data) => {
338
+ const styleBody = AnnotationStyleContextBuilder(this.annotationConfig).toAnnotationBody(type);
339
+ const builder = (0, _ghentcdh_w3c_utils.w3cAnnotation)().setMotivation("tagging").setId(createId()).addBody(styleBody);
340
+ if (data && Object.keys(data).length > 0) {
341
+ data.type = data.type ?? "AnnotationMetadata";
342
+ data.purpose = data.purpose ?? getAnnotationType(builder);
343
+ builder.updateBodyByType(data.type, data);
344
+ }
345
+ builder.addTarget({ source: sourceAnnotation.id }).addTarget({ source: targetAnnotation.id });
346
+ return builder.build();
347
+ };
348
+ cancel() {
349
+ this.setAnnotations(this.annotations, this.allowedChildrenPerType);
350
+ }
351
+ getSourceUri = (annotation) => {
352
+ const builder = this.getBuilder(annotation);
353
+ const sourceUri = builder.getSourceUri();
354
+ if (!sourceUri) {
355
+ console.warn("no source uri");
356
+ return null;
357
+ }
358
+ return {
359
+ textPositionSelector: builder.getTextPositionSelector(sourceUri)[0],
360
+ sourceUri
361
+ };
362
+ };
363
+ getMetadata = (annotation) => {
364
+ return this.getBuilder(annotation).getBodiesByType("AnnotationMetadata")?.[0] ?? null;
365
+ };
366
+ getAnnotationStyle = (annotation) => {
367
+ return getAnnotationStyle(this.getBuilder(annotation));
368
+ };
369
+ getAnnotationType = (annotation) => {
370
+ return getAnnotationType(this.getBuilder(annotation));
371
+ };
372
+ createAnnotationFromSelector(type, annotation, selector) {
373
+ const builder = (0, _ghentcdh_w3c_utils.w3cAnnotation)(annotation ?? void 0).setMotivation("tagging").setId(createId());
374
+ const styleBody = AnnotationStyleContextBuilder(this.annotationConfig).toAnnotationBody(type);
375
+ builder.addBody(styleBody);
376
+ if (selector) updateSelector(builder, selector);
377
+ return builder.build();
378
+ }
379
+ };
380
+ var annotationUtils = (annotationConfig) => {
381
+ return new AnnotationUtilsImpl(annotationConfig);
382
+ };
383
+ //#endregion
384
+ //#region ../annotation-core/src/lib/utils/annotation-render.style.ts
385
+ var defaultRender = (utils) => (annotation) => {
386
+ return (utils?.getAnnotationStyle(annotation))?.target ?? "default";
387
+ };
388
+ var styleFn = (listStyles, utils) => (annotation) => {
389
+ const style = utils?.getAnnotationStyle(annotation);
390
+ if (!style) return "default";
391
+ const styleId = style?.id ?? "default";
392
+ if (!listStyles.includes(styleId)) {
393
+ _ghentcdh_annotated_text.Debugger.debug("styleFn", `No style found for ${styleId}`);
394
+ if (style.color) return { default: (0, _ghentcdh_annotated_text.createHighlightStyle)(style.color) };
395
+ return "default";
396
+ }
397
+ return styleId;
398
+ };
399
+ //#endregion
400
+ //#region ../annotation-core/src/lib/utils/annotation-configuration.factory.ts
401
+ var groupById = (defs, valueKey) => {
402
+ if (!defs) return {};
403
+ return defs.reduce((acc, def) => {
404
+ acc[def.id] = valueKey ? def[valueKey] : def;
405
+ return acc;
406
+ }, {});
407
+ };
408
+ var createAnnotationConfiguration = (annotationDefinitions, utils, textAdapter, annotationAdapter) => {
409
+ const definitions = annotationDefinitions ?? [];
410
+ const definitionsMap = groupById(definitions);
411
+ const rootTypes = definitions.filter((d) => d.annotation.isRoot).map((d) => ({
412
+ key: d.id,
413
+ label: d.label
414
+ }));
415
+ const styles = groupById(definitions, "style");
416
+ if (!styles["default"]) styles["default"] = {
417
+ label: "Annotation",
418
+ isRoot: true,
419
+ style: { default: (0, _ghentcdh_annotated_text.createHighlightStyle)("#dd7777") },
420
+ allowedChildren: [],
421
+ allowedLinks: [],
422
+ views: {}
423
+ };
424
+ const listStyles = Object.keys(styles);
425
+ const allowedChildrenPerType = groupById(definitions, "allowedChildren");
426
+ const defaultAnnotationAdapter = (source) => (0, _ghentcdh_annotated_text.W3CAnnotationAdapter)(source ? { sourceUri: source.uri } : {});
427
+ const renderParams = () => ({ renderFn: defaultRender(utils) });
428
+ const styleParams = () => ({ styleFn: styleFn(listStyles, utils) });
429
+ const _createAnnotatedText = (id, sourceModel) => {
430
+ const _textAdapter = textAdapter?.() ?? (0, _ghentcdh_annotated_text.PlainTextAdapter)();
431
+ const annotatedText = (0, _ghentcdh_annotated_text.createAnnotatedText)(id, {
432
+ annotationAdapter: annotationAdapter?.() ?? defaultAnnotationAdapter(sourceModel),
433
+ textAdapter: _textAdapter
434
+ });
435
+ annotatedText.setSnapper(new _ghentcdh_annotated_text.WordSnapper()).setRenderParams(renderParams()).setStyleParams(styleParams()).registerStyles(styles);
436
+ if (sourceModel) {
437
+ const { content } = sourceModel;
438
+ annotatedText.setText(content.text).setTextAdapterParams({ textDirection: content.textDirection });
439
+ }
440
+ return annotatedText;
441
+ };
442
+ return {
443
+ allowedChildrenPerType,
444
+ definitions,
445
+ getDefinition: (id) => {
446
+ return definitionsMap[id] ?? void 0;
447
+ },
448
+ rootTypes,
449
+ createAnnotatedText: _createAnnotatedText
450
+ };
451
+ };
452
+ //#endregion
453
+ //#region src/lib/utils/annotation.context-builder.ts
454
+ var ANNOTATION_DEF_CONFIG_TOKEN = Symbol("ANNOTATION_DEF_CONFIG_TOKEN");
455
+ //#endregion
456
+ //#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorateMetadata.js
457
+ function __decorateMetadata(k, v) {
458
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
459
+ }
460
+ //#endregion
461
+ //#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorateParam.js
462
+ function __decorateParam(paramIndex, decorator) {
463
+ return function(target, key) {
464
+ decorator(target, key, paramIndex);
465
+ };
466
+ }
467
+ //#endregion
468
+ //#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorate.js
469
+ function __decorate(decorators, target, key, desc) {
470
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
471
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
472
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
473
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
474
+ }
475
+ //#endregion
476
+ //#region src/lib/context/annotation-context.service.ts
477
+ var AnnotationContextService = class AnnotationContextService {
478
+ configRegistry;
479
+ annotationDefConfig;
480
+ contextConfigMap = /* @__PURE__ */ new Map();
481
+ prefixMap = /* @__PURE__ */ new Map();
482
+ constructor(configRegistry, annotationDefConfig) {
483
+ this.configRegistry = configRegistry;
484
+ this.annotationDefConfig = annotationDefConfig;
485
+ }
486
+ async reloadAll() {
487
+ this.contextConfigMap.clear();
488
+ this.configRegistry.findAll().forEach((resource) => {
489
+ const context = createAnnotationContext(this.annotationDefConfig, resource);
490
+ this.contextConfigMap.set(resource.id, context);
491
+ this.prefixMap.set(context.prefix, resource.id);
492
+ });
493
+ }
494
+ async findById(annotationId) {
495
+ const find = this.contextConfigMap.get(annotationId);
496
+ if (find) return find;
497
+ const resource = await this.configRegistry.findById(annotationId);
498
+ if (!resource) return null;
499
+ const context = createAnnotationContext(this.annotationDefConfig, resource);
500
+ this.contextConfigMap.set(annotationId, context);
501
+ return context;
502
+ }
503
+ getResourceIdFromUri = (uri) => {
504
+ for (const prefix of this.prefixMap.keys()) if (uri.startsWith(prefix)) return uri.substring(prefix.length);
505
+ return null;
506
+ };
507
+ };
508
+ AnnotationContextService = __decorate([
509
+ (0, _nestjs_common.Injectable)(),
510
+ __decorateParam(0, (0, _nestjs_common.Inject)(_ghentcdh_crouton_api.ResourceConfigRegistry)),
511
+ __decorateParam(1, (0, _nestjs_common.Inject)(ANNOTATION_DEF_CONFIG_TOKEN)),
512
+ __decorateMetadata("design:paramtypes", [typeof _ghentcdh_crouton_api.ResourceConfigRegistry === "undefined" ? Object : _ghentcdh_crouton_api.ResourceConfigRegistry, Object])
513
+ ], AnnotationContextService);
514
+ //#endregion
515
+ //#region src/lib/annotation/annotation.mapper.service.ts
516
+ var AnnotationW3cMapperService = class AnnotationW3cMapperService {
517
+ contextService;
518
+ constructor(contextService) {
519
+ this.contextService = contextService;
520
+ }
521
+ async getW3CAnnotation(type, annotation) {
522
+ const annotationDef = await this.contextService.findById(type);
523
+ return this.mapToW3CAnnotation(annotationDef, annotation);
524
+ }
525
+ async fromW3CAnnotation(type, annotation) {
526
+ const annotationDef = await this.contextService.findById(type);
527
+ return this.mapFromW3CAnnotation(annotationDef, annotation);
528
+ }
529
+ };
530
+ AnnotationW3cMapperService = __decorate([__decorateParam(0, (0, _nestjs_common.Inject)(AnnotationContextService)), __decorateMetadata("design:paramtypes", [typeof AnnotationContextService === "undefined" ? Object : AnnotationContextService])], AnnotationW3cMapperService);
531
+ //#endregion
532
+ //#region src/lib/prefix.ts
533
+ var SCHEMA_PREFIX = "annotation-editor";
534
+ //#endregion
535
+ //#region src/lib/annotation-namespace.controller.ts
536
+ var AnnotationNamespaceController = class AnnotationNamespaceController {
537
+ service;
538
+ annotationContextService;
539
+ constructor(service, annotationContextService) {
540
+ this.service = service;
541
+ this.annotationContextService = annotationContextService;
542
+ }
543
+ async listNames() {
544
+ const basePath = process.env["API_URL"] ?? "";
545
+ const base = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
546
+ return { annotations: (await this.service.getAll()).map((a) => ({
547
+ id: a.id,
548
+ name: a.name,
549
+ schemas: `${base}/${SCHEMA_PREFIX}/${a.id}/schemas`,
550
+ jsonld: `${base}/ns/${a.id}.jsonld`
551
+ })) };
552
+ }
553
+ async getJsonLd_(id) {
554
+ return (await this.annotationContextService.findById(id))?.jsonLd;
555
+ }
556
+ };
557
+ __decorate([
558
+ (0, _nestjs_common.Get)(),
559
+ __decorateMetadata("design:type", Function),
560
+ __decorateMetadata("design:paramtypes", []),
561
+ __decorateMetadata("design:returntype", Promise)
562
+ ], AnnotationNamespaceController.prototype, "listNames", null);
563
+ __decorate([
564
+ (0, _nestjs_common.Get)(":id.jsonld"),
565
+ __decorateParam(0, (0, _nestjs_common.Param)("id")),
566
+ __decorateMetadata("design:type", Function),
567
+ __decorateMetadata("design:paramtypes", [String]),
568
+ __decorateMetadata("design:returntype", Promise)
569
+ ], AnnotationNamespaceController.prototype, "getJsonLd_", null);
570
+ AnnotationNamespaceController = __decorate([
571
+ (0, _nestjs_common.Controller)("ns"),
572
+ (0, _nestjs_swagger.ApiTags)("Annotations NS"),
573
+ __decorateParam(0, (0, _nestjs_common.Inject)(_ghentcdh_crouton_api.ResourceConfigRegistry)),
574
+ __decorateParam(1, (0, _nestjs_common.Inject)(ANNOTATION_DEF_CONFIG_TOKEN)),
575
+ __decorateMetadata("design:paramtypes", [typeof _ghentcdh_crouton_api.ResourceConfigRegistry === "undefined" ? Object : _ghentcdh_crouton_api.ResourceConfigRegistry, Object])
576
+ ], AnnotationNamespaceController);
577
+ //#endregion
578
+ //#region src/lib/annotation/annotation.controller.ts
579
+ var AnnotationController = class AnnotationController {
580
+ annotationRepository;
581
+ wrapper;
582
+ contextService;
583
+ constructor(annotationRepository, wrapper, contextService) {
584
+ this.annotationRepository = annotationRepository;
585
+ this.wrapper = wrapper;
586
+ this.contextService = contextService;
587
+ }
588
+ async create(type, annotationBody) {
589
+ const parsed = await this.wrapper.fromW3CAnnotation(type, annotationBody);
590
+ const annotation = await this.annotationRepository.create(parsed);
591
+ return this.get(annotation.id);
592
+ }
593
+ async getByType(id) {
594
+ const { annotation, type } = await this.annotationRepository.findOne(id);
595
+ return this.wrapper.getW3CAnnotation(type, annotation);
596
+ }
597
+ async get(id) {
598
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
599
+ const { annotation, type } = await this.annotationRepository.findOne(_id);
600
+ return this.wrapper.getW3CAnnotation(type, annotation);
601
+ }
602
+ async patch(type, id, annotationBody) {
603
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
604
+ const _annotation = await this.wrapper.fromW3CAnnotation(type, annotationBody);
605
+ const annotation = await this.annotationRepository.update(_id, _annotation);
606
+ return this.get(annotation.id);
607
+ }
608
+ async delete(id) {
609
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
610
+ return this.annotationRepository.delete(_id);
611
+ }
612
+ async deleteType(id) {
613
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
614
+ return this.annotationRepository.delete(_id);
615
+ }
616
+ };
617
+ __decorate([
618
+ (0, _nestjs_common.Post)(":type"),
619
+ (0, _nestjs_swagger.ApiOperation)({ summary: "Create a W3C annotation" }),
620
+ (0, _nestjs_swagger.ApiBody)({ description: "W3C annotation body" }),
621
+ (0, _nestjs_swagger.ApiResponse)({
622
+ status: 201,
623
+ description: "The created W3C annotation"
624
+ }),
625
+ __decorateParam(0, (0, _nestjs_common.Param)("type")),
626
+ __decorateParam(1, (0, _nestjs_common.Body)()),
627
+ __decorateMetadata("design:type", Function),
628
+ __decorateMetadata("design:paramtypes", [String, Object]),
629
+ __decorateMetadata("design:returntype", Promise)
630
+ ], AnnotationController.prototype, "create", null);
631
+ __decorate([
632
+ (0, _nestjs_common.Get)(":type/:id"),
633
+ (0, _nestjs_swagger.ApiOperation)({ summary: "Get one annotation by id" }),
634
+ (0, _nestjs_swagger.ApiParam)({
635
+ name: "id",
636
+ type: "string"
637
+ }),
638
+ (0, _nestjs_swagger.ApiParam)({
639
+ name: "type",
640
+ type: "string"
641
+ }),
642
+ (0, _nestjs_swagger.ApiResponse)({
643
+ status: 200,
644
+ description: "The W3C annotation"
645
+ }),
646
+ __decorateParam(0, (0, _nestjs_common.Param)("id")),
647
+ __decorateMetadata("design:type", Function),
648
+ __decorateMetadata("design:paramtypes", [String]),
649
+ __decorateMetadata("design:returntype", Promise)
650
+ ], AnnotationController.prototype, "getByType", null);
651
+ __decorate([
652
+ (0, _nestjs_common.Get)(":id"),
653
+ (0, _nestjs_swagger.ApiOperation)({ summary: "Get one annotation by id" }),
654
+ (0, _nestjs_swagger.ApiParam)({
655
+ name: "id",
656
+ type: "string"
657
+ }),
658
+ (0, _nestjs_swagger.ApiResponse)({
659
+ status: 200,
660
+ description: "The W3C annotation"
661
+ }),
662
+ __decorateParam(0, (0, _nestjs_common.Param)("id")),
663
+ __decorateMetadata("design:type", Function),
664
+ __decorateMetadata("design:paramtypes", [String]),
665
+ __decorateMetadata("design:returntype", Promise)
666
+ ], AnnotationController.prototype, "get", null);
667
+ __decorate([
668
+ (0, _nestjs_common.Patch)(":type/:id"),
669
+ (0, _nestjs_swagger.ApiOperation)({ summary: "Update an annotation" }),
670
+ (0, _nestjs_swagger.ApiParam)({
671
+ name: "id",
672
+ type: "string"
673
+ }),
674
+ (0, _nestjs_swagger.ApiBody)({ description: "W3C annotation body" }),
675
+ (0, _nestjs_swagger.ApiResponse)({
676
+ status: 200,
677
+ description: "The updated W3C annotation"
678
+ }),
679
+ __decorateParam(0, (0, _nestjs_common.Param)("type")),
680
+ __decorateParam(1, (0, _nestjs_common.Param)("id")),
681
+ __decorateParam(2, (0, _nestjs_common.Body)()),
682
+ __decorateMetadata("design:type", Function),
683
+ __decorateMetadata("design:paramtypes", [
684
+ String,
685
+ String,
686
+ Object
687
+ ]),
688
+ __decorateMetadata("design:returntype", Promise)
689
+ ], AnnotationController.prototype, "patch", null);
690
+ __decorate([
691
+ (0, _nestjs_common.Delete)(":id"),
692
+ (0, _nestjs_swagger.ApiOperation)({ summary: "Delete an annotation" }),
693
+ (0, _nestjs_swagger.ApiParam)({
694
+ name: "id",
695
+ type: "string"
696
+ }),
697
+ (0, _nestjs_swagger.ApiResponse)({
698
+ status: 200,
699
+ description: "Annotation deleted"
700
+ }),
701
+ __decorateParam(0, (0, _nestjs_common.Param)("id")),
702
+ __decorateMetadata("design:type", Function),
703
+ __decorateMetadata("design:paramtypes", [String]),
704
+ __decorateMetadata("design:returntype", Promise)
705
+ ], AnnotationController.prototype, "delete", null);
706
+ __decorate([
707
+ (0, _nestjs_common.Delete)(":type/:id"),
708
+ (0, _nestjs_swagger.ApiOperation)({ summary: "Delete an annotation" }),
709
+ (0, _nestjs_swagger.ApiParam)({
710
+ name: "id",
711
+ type: "string"
712
+ }),
713
+ (0, _nestjs_swagger.ApiResponse)({
714
+ status: 200,
715
+ description: "Annotation deleted"
716
+ }),
717
+ __decorateParam(0, (0, _nestjs_common.Param)("id")),
718
+ __decorateMetadata("design:type", Function),
719
+ __decorateMetadata("design:paramtypes", [String]),
720
+ __decorateMetadata("design:returntype", Promise)
721
+ ], AnnotationController.prototype, "deleteType", null);
722
+ AnnotationController = __decorate([
723
+ (0, _nestjs_common.Controller)(`${SCHEMA_PREFIX}/annotation`),
724
+ (0, _nestjs_swagger.ApiTags)("Annotations"),
725
+ __decorateParam(0, (0, _nestjs_common.Inject)(AnnotationCrudRepository)),
726
+ __decorateParam(1, (0, _nestjs_common.Inject)(AnnotationW3cMapperService)),
727
+ __decorateParam(2, (0, _nestjs_common.Inject)(AnnotationContextService)),
728
+ __decorateMetadata("design:paramtypes", [
729
+ typeof AnnotationCrudRepository === "undefined" ? Object : AnnotationCrudRepository,
730
+ typeof AnnotationW3cMapperService === "undefined" ? Object : AnnotationW3cMapperService,
731
+ typeof AnnotationContextService === "undefined" ? Object : AnnotationContextService
732
+ ])
733
+ ], AnnotationController);
734
+ //#endregion
735
+ //#region src/lib/utils/schemaEnricher.utils.ts
736
+ var createSchemaEnricher = (baseUrl = "") => (schema) => {
737
+ const uri = `${baseUrl}${SCHEMA_PREFIX}/annotation/${schema.route}`;
738
+ const uriId = `${uri}/{id}`;
739
+ schema.operations = {
740
+ findOne: schema.operations.findOne ?? {
741
+ uri: uriId,
742
+ method: "get"
743
+ },
744
+ update: schema.operations.update ?? {
745
+ uri: uriId,
746
+ method: "patch"
747
+ },
748
+ delete: schema.operations.delete ?? {
749
+ uri: uriId,
750
+ method: "delete"
751
+ },
752
+ create: schema.operations.create ?? {
753
+ uri,
754
+ method: "post"
755
+ },
756
+ findAll: schema.operations.findAll
757
+ };
758
+ return { ...schema };
759
+ };
760
+ //#endregion
761
+ //#region src/lib/annotation-api.module.ts
762
+ var _AnnotationApiModule;
763
+ (0, _ghentcdh_crouton_core.registerResourceExtensions)({ annotation: AnnotationConfigSchema });
764
+ var AnnotationApiModule = _AnnotationApiModule = class AnnotationApiModule {
765
+ static async forResourceDir(resourcePath, datasourcePath, config, annotation) {
766
+ const _config = resolveConfig(config);
767
+ const crouton = await _ghentcdh_crouton_api.CroutonApiModule.forResourceDir(resourcePath, datasourcePath, {
768
+ baseUrl: "",
769
+ prefix: SCHEMA_PREFIX,
770
+ extensions: { annotation: AnnotationConfigSchema },
771
+ schemaEnricher: createSchemaEnricher(_config.baseUrl)
772
+ });
773
+ if (annotation) return {
774
+ module: _AnnotationApiModule,
775
+ global: true,
776
+ imports: [crouton],
777
+ controllers: [AnnotationNamespaceController, AnnotationController],
778
+ providers: [
779
+ AnnotationContextService,
780
+ {
781
+ provide: ANNOTATION_DEF_CONFIG_TOKEN,
782
+ useValue: _config
783
+ },
784
+ {
785
+ provide: AnnotationCrudRepository,
786
+ useExisting: annotation.repository
787
+ },
788
+ {
789
+ provide: AnnotationW3cMapperService,
790
+ useExisting: annotation.mapper
791
+ }
792
+ ],
793
+ exports: [AnnotationContextService]
794
+ };
795
+ return {
796
+ module: _AnnotationApiModule,
797
+ global: true,
798
+ imports: [crouton],
799
+ controllers: [AnnotationNamespaceController],
800
+ providers: [AnnotationContextService, {
801
+ provide: ANNOTATION_DEF_CONFIG_TOKEN,
802
+ useValue: _config
803
+ }],
804
+ exports: [AnnotationContextService]
805
+ };
806
+ }
807
+ };
808
+ AnnotationApiModule = _AnnotationApiModule = __decorate([(0, _nestjs_common.Module)({
809
+ controllers: [],
810
+ providers: [],
811
+ exports: []
812
+ })], AnnotationApiModule);
813
+ //#endregion
814
+ Object.defineProperty(exports, "AnnotationApiModule", {
815
+ enumerable: true,
816
+ get: function() {
817
+ return AnnotationApiModule;
818
+ }
819
+ });
820
+ exports.AnnotationConfigSchema = AnnotationConfigSchema;
821
+ Object.defineProperty(exports, "AnnotationContextService", {
822
+ enumerable: true,
823
+ get: function() {
824
+ return AnnotationContextService;
825
+ }
826
+ });
827
+ exports.AnnotationCrudRepository = AnnotationCrudRepository;
828
+ exports.AnnotationJsonResourceSchema = AnnotationJsonResourceSchema;
829
+ exports.AnnotationJsonResourceShape = AnnotationJsonResourceShape;
830
+ exports.AnnotationMetadataType = AnnotationMetadataType;
831
+ exports.AnnotationResourceSchema = AnnotationResourceSchema;
832
+ exports.AnnotationStyleContextBuilder = AnnotationStyleContextBuilder;
833
+ exports.AnnotationStyleType = AnnotationStyleType;
834
+ Object.defineProperty(exports, "AnnotationW3cMapperService", {
835
+ enumerable: true,
836
+ get: function() {
837
+ return AnnotationW3cMapperService;
838
+ }
839
+ });
840
+ exports.BASELINE_RESOURCE_VERSION = BASELINE_RESOURCE_VERSION;
841
+ exports.CURRENT_RESOURCE_VERSION = CURRENT_RESOURCE_VERSION;
842
+ exports.KeyLabelSchema = KeyLabelSchema;
843
+ exports.SourceModelSchema = SourceModelSchema;
844
+ exports.SourceTextSchema = SourceTextSchema;
845
+ exports.annotationColumnDefinition = annotationColumnDefinition;
846
+ exports.annotationUtils = annotationUtils;
847
+ exports.baseContextBuilder = baseContextBuilder;
848
+ exports.buildGridStyle = buildGridStyle;
849
+ exports.buildPrefix = buildPrefix;
850
+ exports.createAnnotationConfiguration = createAnnotationConfiguration;
851
+ exports.createAnnotationContext = createAnnotationContext;
852
+ exports.createAnnotationStyleBodyUnsafe = createAnnotationStyleBodyUnsafe;
853
+ exports.defaultRender = defaultRender;
854
+ exports.getPaneArea = getPaneArea;
855
+ exports.resolveConfig = resolveConfig;
856
+ exports.styleFn = styleFn;