@adatechnology/content-contracts 0.1.0 → 0.3.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.
package/dist/index.js CHANGED
@@ -13,6 +13,11 @@ function isPostStatus(value) {
13
13
  return typeof value === "string" && POST_STATUSES.includes(value);
14
14
  }
15
15
  __name(isPostStatus, "isPostStatus");
16
+ var RECURRENCE_FREQUENCY = {
17
+ WEEKLY: "weekly",
18
+ MONTHLY: "monthly"
19
+ };
20
+ var RECURRENCE_FREQUENCIES = Object.values(RECURRENCE_FREQUENCY);
16
21
 
17
22
  // src/errors.ts
18
23
  var ContentError = class extends Error {
@@ -33,7 +38,12 @@ var CONTENT_ERROR_CODES = {
33
38
  INVALID_SLUG: "CONTENT_INVALID_SLUG",
34
39
  CONFIG_MISSING: "CONTENT_CONFIG_MISSING",
35
40
  INVALID_IMAGE: "CONTENT_INVALID_IMAGE",
36
- IMAGE_STORAGE_DISABLED: "CONTENT_IMAGE_STORAGE_DISABLED"
41
+ IMAGE_STORAGE_DISABLED: "CONTENT_IMAGE_STORAGE_DISABLED",
42
+ NOT_A_TEMPLATE: "CONTENT_NOT_A_TEMPLATE",
43
+ TEMPLATE_NOT_PUBLISHABLE: "CONTENT_TEMPLATE_NOT_PUBLISHABLE",
44
+ NOT_PUBLISHED: "CONTENT_NOT_PUBLISHED",
45
+ REPUBLISH_DATE_IN_FUTURE: "CONTENT_REPUBLISH_DATE_IN_FUTURE",
46
+ RECURRENCE_NOT_FOUND: "CONTENT_RECURRENCE_NOT_FOUND"
37
47
  };
38
48
  var PostNotFoundError = class extends ContentError {
39
49
  static {
@@ -98,6 +108,58 @@ var ImageStorageDisabledError = class extends ContentError {
98
108
  super("Envio de imagem n\xE3o configurado.", 501, CONTENT_ERROR_CODES.IMAGE_STORAGE_DISABLED);
99
109
  }
100
110
  };
111
+ var NotATemplateError = class extends ContentError {
112
+ static {
113
+ __name(this, "NotATemplateError");
114
+ }
115
+ postId;
116
+ constructor(postId) {
117
+ super("Este post n\xE3o \xE9 um modelo.", 422, CONTENT_ERROR_CODES.NOT_A_TEMPLATE, {
118
+ postId
119
+ }), this.postId = postId;
120
+ }
121
+ };
122
+ var TemplateNotPublishableError = class extends ContentError {
123
+ static {
124
+ __name(this, "TemplateNotPublishableError");
125
+ }
126
+ postId;
127
+ constructor(postId) {
128
+ super("Modelo n\xE3o pode ser publicado: crie um post a partir dele.", 422, CONTENT_ERROR_CODES.TEMPLATE_NOT_PUBLISHABLE, {
129
+ postId
130
+ }), this.postId = postId;
131
+ }
132
+ };
133
+ var PostNotPublishedError = class extends ContentError {
134
+ static {
135
+ __name(this, "PostNotPublishedError");
136
+ }
137
+ postId;
138
+ constructor(postId) {
139
+ super("S\xF3 post publicado pode ser republicado.", 422, CONTENT_ERROR_CODES.NOT_PUBLISHED, {
140
+ postId
141
+ }), this.postId = postId;
142
+ }
143
+ };
144
+ var RepublishDateInFutureError = class extends ContentError {
145
+ static {
146
+ __name(this, "RepublishDateInFutureError");
147
+ }
148
+ constructor() {
149
+ super("A nova data n\xE3o pode ser futura: o post sairia do ar at\xE9 l\xE1.", 422, CONTENT_ERROR_CODES.REPUBLISH_DATE_IN_FUTURE);
150
+ }
151
+ };
152
+ var RecurrenceNotFoundError = class extends ContentError {
153
+ static {
154
+ __name(this, "RecurrenceNotFoundError");
155
+ }
156
+ reference;
157
+ constructor(reference) {
158
+ super("Recorr\xEAncia n\xE3o encontrada.", 404, CONTENT_ERROR_CODES.RECURRENCE_NOT_FOUND, {
159
+ reference
160
+ }), this.reference = reference;
161
+ }
162
+ };
101
163
 
102
164
  // src/schemas.ts
103
165
  import { z } from "zod";
@@ -123,6 +185,58 @@ function withSlugSuffix(slug, attempt) {
123
185
  return `${slug.slice(0, SLUG_MAX_LENGTH - suffix.length).replace(/-+$/g, "")}${suffix}`;
124
186
  }
125
187
  __name(withSlugSuffix, "withSlugSuffix");
188
+ var DEFAULT_SHORT_SLUG_LENGTH = 60;
189
+ var PT_BR_STOP_WORDS = [
190
+ "a",
191
+ "as",
192
+ "o",
193
+ "os",
194
+ "um",
195
+ "uma",
196
+ "uns",
197
+ "umas",
198
+ "de",
199
+ "da",
200
+ "das",
201
+ "do",
202
+ "dos",
203
+ "em",
204
+ "na",
205
+ "nas",
206
+ "no",
207
+ "nos",
208
+ "e",
209
+ "ou",
210
+ "para",
211
+ "pra",
212
+ "pro",
213
+ "por",
214
+ "pelo",
215
+ "pela",
216
+ "pelos",
217
+ "pelas",
218
+ "com",
219
+ "sem",
220
+ "ao",
221
+ "aos",
222
+ "que",
223
+ "se"
224
+ ];
225
+ function buildShortSlug(title, options = {}) {
226
+ const maxLength = Math.min(options.maxLength ?? DEFAULT_SHORT_SLUG_LENGTH, SLUG_MAX_LENGTH);
227
+ const words = slugify(title).split("-").filter(Boolean);
228
+ const stop = new Set(options.stopWords === false ? [] : options.stopWords ?? PT_BR_STOP_WORDS);
229
+ const meaningful = words.filter((word) => !stop.has(word));
230
+ const kept = meaningful.length > 0 ? meaningful : words;
231
+ let slug = "";
232
+ for (const word of kept) {
233
+ const next = slug ? `${slug}-${word}` : word;
234
+ if (next.length > maxLength) break;
235
+ slug = next;
236
+ }
237
+ return slug || (kept[0] ?? "").slice(0, maxLength).replace(/-+$/g, "");
238
+ }
239
+ __name(buildShortSlug, "buildShortSlug");
126
240
 
127
241
  // src/tags.ts
128
242
  var TAG_MAX_LENGTH = 40;
@@ -143,6 +257,25 @@ function normalizeTags(values) {
143
257
  return result.slice(0, TAGS_MAX_COUNT);
144
258
  }
145
259
  __name(normalizeTags, "normalizeTags");
260
+ function buildTagLabels(params) {
261
+ const labels = {};
262
+ for (const value of params.typed) {
263
+ const tag = normalizeTag(value);
264
+ if (!tag) continue;
265
+ const typed = value.trim().replace(/\s+/g, " ").slice(0, TAG_MAX_LENGTH);
266
+ const label = params.explicit?.[tag]?.trim() || (typed !== tag ? typed : void 0) || params.previous?.[tag];
267
+ if (label && label !== tag) labels[tag] = label;
268
+ }
269
+ return labels;
270
+ }
271
+ __name(buildTagLabels, "buildTagLabels");
272
+ function formatTagLabel(tag, labels) {
273
+ const stored = labels?.[tag];
274
+ if (stored) return stored;
275
+ const spaced = tag.replace(/-+/g, " ").trim();
276
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
277
+ }
278
+ __name(formatTagLabel, "formatTagLabel");
146
279
 
147
280
  // src/schemas.ts
148
281
  var POST_LIMITS = {
@@ -173,6 +306,8 @@ var postFieldsSchema = z.object({
173
306
  coverImageUrl: httpUrlSchema.nullable().optional(),
174
307
  coverImageAlt: optionalText(POST_LIMITS.IMAGE_ALT),
175
308
  tags: z.array(z.string().trim().min(1).max(TAG_MAX_LENGTH)).max(TAGS_MAX_COUNT).optional(),
309
+ /** Rótulo de exibição por tag (chave = tag normalizada). Sem rótulo, vale o texto digitado. */
310
+ tagLabels: z.record(z.string().trim().min(1).max(TAG_MAX_LENGTH)).optional(),
176
311
  authorName: optionalText(POST_LIMITS.AUTHOR_NAME),
177
312
  seoTitle: optionalText(POST_LIMITS.SEO_TITLE),
178
313
  seoDescription: optionalText(POST_LIMITS.SEO_DESCRIPTION),
@@ -188,18 +323,62 @@ var publishPostSchema = z.object({
188
323
  }).optional()
189
324
  }).strict();
190
325
  var pageSchema = z.coerce.number().int().min(1).max(1e4).default(1);
326
+ var POST_SORT_FIELDS = [
327
+ "title",
328
+ "status",
329
+ "publishedAt",
330
+ "updatedAt"
331
+ ];
191
332
  var listPostsQuerySchema = z.object({
192
333
  page: pageSchema,
193
334
  pageSize: z.coerce.number().int().min(1).max(POST_LIMITS.ADMIN_PAGE_SIZE).default(20),
194
335
  status: z.enum(POST_STATUSES).optional(),
195
- tag: z.string().trim().min(1).max(TAG_MAX_LENGTH).optional(),
196
- search: z.string().trim().min(1).max(POST_LIMITS.SEARCH).optional()
336
+ /** Uma tag, ou várias separadas por vírgula (basta ter UMA delas). */
337
+ tag: z.string().trim().min(1).max(TAG_MAX_LENGTH * TAGS_MAX_COUNT).optional(),
338
+ search: z.string().trim().min(1).max(POST_LIMITS.SEARCH).optional(),
339
+ /** Padrão: `updatedAt` (o que o painel mexeu por último). */
340
+ sort: z.enum(POST_SORT_FIELDS).default("updatedAt"),
341
+ order: z.enum([
342
+ "asc",
343
+ "desc"
344
+ ]).default("desc"),
345
+ /** `true`: só modelos. Ausente/`false`: só posts (modelo nunca aparece misturado na lista). */
346
+ isTemplate: z.union([
347
+ z.boolean(),
348
+ z.enum([
349
+ "true",
350
+ "false"
351
+ ])
352
+ ]).transform((value) => value === true || value === "true").optional()
197
353
  });
198
354
  var listPublishedPostsQuerySchema = z.object({
199
355
  page: pageSchema,
200
356
  pageSize: z.coerce.number().int().min(1).max(POST_LIMITS.PUBLIC_PAGE_SIZE).default(10),
201
357
  tag: z.string().trim().min(1).max(TAG_MAX_LENGTH).optional()
202
358
  });
359
+ var isoInstant = z.string().datetime({
360
+ offset: true
361
+ });
362
+ var saveAsTemplateSchema = z.object({
363
+ title: z.string().trim().min(1).max(POST_LIMITS.TITLE).optional()
364
+ }).strict();
365
+ var createFromTemplateSchema = z.object({
366
+ title: z.string().trim().min(1).max(POST_LIMITS.TITLE).optional(),
367
+ slug: slugSchema.optional()
368
+ }).strict();
369
+ var republishPostSchema = z.object({
370
+ publishedAt: isoInstant.optional()
371
+ }).strict();
372
+ var createRecurrenceSchema = z.object({
373
+ templateId: z.string().uuid(),
374
+ frequency: z.enum(RECURRENCE_FREQUENCIES),
375
+ /** Primeira publicação automática. */
376
+ startsAt: isoInstant
377
+ }).strict();
378
+ var updateRecurrenceSchema = z.object({
379
+ isActive: z.boolean().optional(),
380
+ nextRunAt: isoInstant.optional()
381
+ }).strict();
203
382
 
204
383
  // src/providers.ts
205
384
  var POST_EVENT = {
@@ -207,13 +386,60 @@ var POST_EVENT = {
207
386
  UPDATED: "updated",
208
387
  PUBLISHED: "published",
209
388
  UNPUBLISHED: "unpublished",
210
- ARCHIVED: "archived"
389
+ ARCHIVED: "archived",
390
+ REPUBLISHED: "republished"
211
391
  };
212
392
  var DEFAULT_ADMIN_SCOPES = [
213
393
  "content:admin"
214
394
  ];
215
395
  var DEFAULT_PUBLIC_CACHE_CONTROL = "public, max-age=60, s-maxage=300, stale-while-revalidate=600";
216
396
 
397
+ // src/postPath.ts
398
+ var SHORT_ID_LENGTH = 6;
399
+ var SHORT_ID_PATTERN = /^[0-9a-z]{6}$/;
400
+ var REF_PATTERN = /^([0-9a-z]{6})-(.+)$/;
401
+ function isShortId(value) {
402
+ return SHORT_ID_PATTERN.test(value);
403
+ }
404
+ __name(isShortId, "isShortId");
405
+ function buildPostRef(params) {
406
+ return `${params.shortId}-${params.slug}`;
407
+ }
408
+ __name(buildPostRef, "buildPostRef");
409
+ function buildPostPath(params) {
410
+ const base = params.basePath.replace(/\/+$/g, "");
411
+ return `${base}/${encodeURIComponent(buildPostRef(params))}`;
412
+ }
413
+ __name(buildPostPath, "buildPostPath");
414
+ function parsePostRef(ref) {
415
+ const slug = ref.trim().toLowerCase();
416
+ const match = REF_PATTERN.exec(slug);
417
+ return match?.[1] ? {
418
+ shortId: match[1],
419
+ slug
420
+ } : {
421
+ slug
422
+ };
423
+ }
424
+ __name(parsePostRef, "parsePostRef");
425
+ function parsePostPath(params) {
426
+ const base = params.basePath.replace(/\/+$/g, "");
427
+ const clean = params.path.split(/[?#]/)[0] ?? "";
428
+ if (!clean.startsWith(`${base}/`)) return void 0;
429
+ const rest = clean.slice(base.length + 1).replace(/\/+$/g, "");
430
+ if (!rest || rest.includes("/")) return void 0;
431
+ try {
432
+ return parsePostRef(decodeURIComponent(rest));
433
+ } catch {
434
+ return void 0;
435
+ }
436
+ }
437
+ __name(parsePostPath, "parsePostPath");
438
+ function isCanonicalPostRef(params) {
439
+ return params.ref.trim().toLowerCase() === buildPostRef(params);
440
+ }
441
+ __name(isCanonicalPostRef, "isCanonicalPostRef");
442
+
217
443
  // src/markdown/sanitizeUrl.ts
218
444
  var LINK_SCHEMES = /* @__PURE__ */ new Set([
219
445
  "http",
@@ -571,6 +797,47 @@ function parseDestination(text, start) {
571
797
  }
572
798
  __name(parseDestination, "parseDestination");
573
799
 
800
+ // src/markdown/paragraphToBlock.ts
801
+ function isFiller(node) {
802
+ return node.type === "break" || node.type === "text" && !node.value.trim();
803
+ }
804
+ __name(isFiller, "isFiller");
805
+ function paragraphToBlock(children) {
806
+ const meaningful = children.filter((node) => !isFiller(node));
807
+ const images = meaningful.filter((node) => node.type === "image");
808
+ if (images.length === 0 || images.length !== meaningful.length) return {
809
+ type: "paragraph",
810
+ children
811
+ };
812
+ const [only] = images;
813
+ if (images.length === 1 && only?.title) {
814
+ return {
815
+ type: "figure",
816
+ image: {
817
+ src: only.src,
818
+ alt: only.alt
819
+ },
820
+ caption: only.title
821
+ };
822
+ }
823
+ if (images.length < 2) return {
824
+ type: "paragraph",
825
+ children
826
+ };
827
+ const gallery = images.map((image) => ({
828
+ src: image.src,
829
+ alt: image.alt,
830
+ ...image.title ? {
831
+ caption: image.title
832
+ } : {}
833
+ }));
834
+ return {
835
+ type: "gallery",
836
+ images: gallery
837
+ };
838
+ }
839
+ __name(paragraphToBlock, "paragraphToBlock");
840
+
574
841
  // src/markdown/parseMarkdown.ts
575
842
  var MAX_BLOCK_DEPTH = 6;
576
843
  var FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/;
@@ -692,10 +959,7 @@ function parseParagraph(lines, index, depth) {
692
959
  cursor += 1;
693
960
  }
694
961
  return {
695
- block: {
696
- type: "paragraph",
697
- children: parseInline(content.join("\n").trimEnd())
698
- },
962
+ block: paragraphToBlock(parseInline(content.join("\n").trimEnd())),
699
963
  next: cursor
700
964
  };
701
965
  }
@@ -807,7 +1071,10 @@ function blockToPlainText(block) {
807
1071
  return block.children.map(blockToPlainText).join("\n\n");
808
1072
  case "list":
809
1073
  return block.items.map((item) => item.map(blockToPlainText).join("\n")).join("\n");
1074
+ case "figure":
1075
+ return block.caption;
810
1076
  case "thematicBreak":
1077
+ case "gallery":
811
1078
  return "";
812
1079
  }
813
1080
  }
@@ -903,6 +1170,12 @@ function renderInlineNode(node, context) {
903
1170
  }
904
1171
  }
905
1172
  __name(renderInlineNode, "renderInlineNode");
1173
+ function renderFigure(image, caption) {
1174
+ const img = `<img src="${escapeHtml(image.src)}" alt="${escapeHtml(image.alt)}" loading="lazy" decoding="async">`;
1175
+ const figcaption = caption ? `<figcaption>${escapeHtml(caption)}</figcaption>` : "";
1176
+ return `<figure class="adc-figure">${img}${figcaption}</figure>`;
1177
+ }
1178
+ __name(renderFigure, "renderFigure");
906
1179
  function renderBlock(block, context, tight = false) {
907
1180
  switch (block.type) {
908
1181
  case "heading": {
@@ -920,6 +1193,10 @@ function renderBlock(block, context, tight = false) {
920
1193
  }
921
1194
  case "thematicBreak":
922
1195
  return "<hr>";
1196
+ case "figure":
1197
+ return renderFigure(block.image, block.caption);
1198
+ case "gallery":
1199
+ return `<div class="adc-gallery" data-count="${block.images.length}">${block.images.map((image) => renderFigure(image, image.caption)).join("")}</div>`;
923
1200
  case "list": {
924
1201
  const tag = block.ordered ? "ol" : "ul";
925
1202
  const start = block.ordered && block.start !== void 0 && block.start !== 1 ? ` start="${block.start}"` : "";
@@ -957,7 +1234,7 @@ function escapeXml(value) {
957
1234
  __name(escapeXml, "escapeXml");
958
1235
  function buildPostUrl(params) {
959
1236
  const base = params.siteUrl.replace(/\/+$/, "");
960
- const path = (params.postPathTemplate ?? DEFAULT_POST_PATH_TEMPLATE).replace("{slug}", encodeURIComponent(params.slug));
1237
+ const path = (params.postPathTemplate ?? DEFAULT_POST_PATH_TEMPLATE).replace("{shortId}", encodeURIComponent(params.shortId ?? "")).replace("{slug}", encodeURIComponent(params.slug));
961
1238
  return `${base}${path.startsWith("/") ? path : `/${path}`}`;
962
1239
  }
963
1240
  __name(buildPostUrl, "buildPostUrl");
@@ -1044,35 +1321,55 @@ export {
1044
1321
  DEFAULT_LINK_REL,
1045
1322
  DEFAULT_POST_PATH_TEMPLATE,
1046
1323
  DEFAULT_PUBLIC_CACHE_CONTROL,
1324
+ DEFAULT_SHORT_SLUG_LENGTH,
1047
1325
  DEFAULT_WORDS_PER_MINUTE,
1048
1326
  DuplicateSlugError,
1049
1327
  ImageStorageDisabledError,
1050
1328
  InvalidCoverImageError,
1051
1329
  InvalidSlugError,
1330
+ NotATemplateError,
1052
1331
  POST_EVENT,
1053
1332
  POST_LIMITS,
1333
+ POST_SORT_FIELDS,
1054
1334
  POST_STATUS,
1055
1335
  POST_STATUSES,
1336
+ PT_BR_STOP_WORDS,
1056
1337
  PostNotFoundError,
1338
+ PostNotPublishedError,
1339
+ RECURRENCE_FREQUENCIES,
1340
+ RECURRENCE_FREQUENCY,
1341
+ RecurrenceNotFoundError,
1342
+ RepublishDateInFutureError,
1343
+ SHORT_ID_LENGTH,
1057
1344
  SLUG_MAX_LENGTH,
1058
1345
  TAGS_MAX_COUNT,
1059
1346
  TAG_MAX_LENGTH,
1347
+ TemplateNotPublishableError,
1060
1348
  buildAtomFeed,
1061
1349
  buildExcerpt,
1350
+ buildPostPath,
1351
+ buildPostRef,
1062
1352
  buildPostUrl,
1063
1353
  buildRssFeed,
1354
+ buildShortSlug,
1064
1355
  buildSitemapXml,
1356
+ buildTagLabels,
1065
1357
  countWords,
1358
+ createFromTemplateSchema,
1066
1359
  createHeadingIdGenerator,
1067
1360
  createPostSchema,
1361
+ createRecurrenceSchema,
1068
1362
  documentToPlainText,
1069
1363
  escapeHtml,
1070
1364
  escapeXml,
1071
1365
  estimateReadingTimeMinutes,
1366
+ formatTagLabel,
1072
1367
  httpUrlSchema,
1073
1368
  inlineToPlainText,
1074
1369
  isAbsoluteHttpUrl,
1370
+ isCanonicalPostRef,
1075
1371
  isPostStatus,
1372
+ isShortId,
1076
1373
  isValidSlug,
1077
1374
  listPostsQuerySchema,
1078
1375
  listPublishedPostsQuerySchema,
@@ -1081,16 +1378,21 @@ export {
1081
1378
  normalizeTags,
1082
1379
  parseInline,
1083
1380
  parseMarkdown,
1381
+ parsePostPath,
1382
+ parsePostRef,
1084
1383
  postFieldsSchema,
1085
1384
  publishPostSchema,
1086
1385
  renderMarkdownDocument,
1087
1386
  renderMarkdownToHtml,
1387
+ republishPostSchema,
1088
1388
  resolveHeadingLevel,
1089
1389
  sanitizeImageUrl,
1090
1390
  sanitizeLinkUrl,
1391
+ saveAsTemplateSchema,
1091
1392
  slugSchema,
1092
1393
  slugify,
1093
1394
  updatePostSchema,
1395
+ updateRecurrenceSchema,
1094
1396
  withSlugSuffix
1095
1397
  };
1096
1398
  //# sourceMappingURL=index.js.map