@jant/core 0.8.1 → 0.9.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 (36) hide show
  1. package/dist/{app--uxnaIRV.js → app-BzH8jmh3.js} +1199 -262
  2. package/dist/client/.vite/manifest.json +2 -2
  3. package/dist/client/_assets/{client-BT6kpcuG.js → client-S8oryJ0m.js} +1 -1
  4. package/dist/client/_assets/{client-auth-begiT1tq.js → client-auth-Ds9G0IgR.js} +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/node.js +2 -2
  7. package/package.json +1 -1
  8. package/src/__tests__/helpers/cursor-walk.ts +37 -7
  9. package/src/app.tsx +4 -0
  10. package/src/lib/__tests__/thread-fold.test.ts +43 -0
  11. package/src/lib/api-posts.ts +110 -2
  12. package/src/lib/api-public-posts.ts +263 -0
  13. package/src/lib/api-threads.ts +207 -0
  14. package/src/lib/thread-fold.ts +83 -41
  15. package/src/lib/thread-query.ts +143 -0
  16. package/src/middleware/cors.ts +8 -1
  17. package/src/middleware/deprecation.ts +48 -0
  18. package/src/routes/api/__tests__/mcp.test.ts +89 -0
  19. package/src/routes/api/__tests__/posts.test.ts +78 -0
  20. package/src/routes/api/__tests__/public-access.test.ts +5 -0
  21. package/src/routes/api/__tests__/threads.test.ts +115 -0
  22. package/src/routes/api/posts.ts +15 -104
  23. package/src/routes/api/public/__tests__/threads.test.ts +363 -0
  24. package/src/routes/api/public/archive.ts +82 -81
  25. package/src/routes/api/public/posts.ts +97 -298
  26. package/src/routes/api/public/threads.ts +141 -0
  27. package/src/routes/api/threads.ts +128 -0
  28. package/src/services/__tests__/thread.test.ts +495 -0
  29. package/src/services/index.ts +4 -0
  30. package/src/services/mcp.ts +208 -53
  31. package/src/services/post.ts +222 -43
  32. package/src/services/thread.ts +392 -0
  33. package/src/types/constants.ts +25 -0
  34. package/src/ui/feed/ThreadPreview.tsx +9 -14
  35. package/src/ui/feed/__tests__/thread-preview.test.ts +18 -22
  36. package/src/ui/feed/thread-preview-state.ts +0 -35
@@ -239,7 +239,7 @@
239
239
  ]
240
240
  },
241
241
  "src/client-auth.ts": {
242
- "file": "_assets/client-auth-begiT1tq.js",
242
+ "file": "_assets/client-auth-Ds9G0IgR.js",
243
243
  "name": "client-auth",
244
244
  "src": "src/client-auth.ts",
245
245
  "isEntry": true,
@@ -306,7 +306,7 @@
306
306
  ]
307
307
  },
308
308
  "src/client.ts": {
309
- "file": "_assets/client-BT6kpcuG.js",
309
+ "file": "_assets/client-S8oryJ0m.js",
310
310
  "name": "client",
311
311
  "src": "src/client.ts",
312
312
  "isEntry": true,
@@ -292,4 +292,4 @@ ${c}`:c;break;case`event`:r.event=c;break;case`id`:e(r.id=c);break;case`retry`:{
292
292
  </div>`}
293
293
  </div>
294
294
  </dialog>
295
- `:t}};customElements.define(`jant-text-preview`,gn);function _n(e){return e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey}function vn(e,t){t&&(e.textContent=t)}function yn(e){let t=e.target;if(!(t instanceof globalThis.Element))return;let n=t.closest(`a[data-note-expand]`);if(!n||_n(e))return;let r=n.closest(`article[data-post]`),i=r?.querySelector(`[data-post-body]`);if(r&&i&&i.querySelector(`[data-note-break]`)){if(e.preventDefault(),i.hasAttribute(`data-note-clamp`)){i.removeAttribute(`data-note-clamp`),n.setAttribute(`aria-expanded`,`true`),vn(n,n.dataset.labelLess);return}i.setAttribute(`data-note-clamp`,``),n.setAttribute(`aria-expanded`,`false`),vn(n,n.dataset.labelMore),r.getBoundingClientRect().top<0&&typeof r.scrollIntoView==`function`&&r.scrollIntoView({block:`start`})}}document.addEventListener(`click`,yn),document.querySelectorAll(`.archive-chip-dropdown`).forEach(e=>{let t=e.querySelector(`:scope > button`),n=e.querySelector(`:scope > [data-popover]`),r=n?n.querySelector(`[role="listbox"]`):null;if(!t||!n||!r)return;let i=Array.from(r.querySelectorAll(`[role="option"]`)),a=e.classList.contains(`archive-chip-media`),o=e.dataset.filterKey,s=new Set;a&&i.forEach(e=>{!e.dataset.navigate&&e.getAttribute(`aria-selected`)===`true`&&s.add(e.dataset.value)});let c=new Set(s),l=()=>{document.dispatchEvent(new CustomEvent(`basecoat:popover`,{detail:{source:e}})),n.setAttribute(`aria-hidden`,`false`),t.setAttribute(`aria-expanded`,`true`),a&&(c=new Set(s))},u=(e=!0)=>{if(n.getAttribute(`aria-hidden`)!==`true`&&(n.setAttribute(`aria-hidden`,`true`),t.setAttribute(`aria-expanded`,`false`),e&&t.focus(),a&&o&&(s.size!==c.size||[...s].some(e=>!c.has(e))))){let e=new URL(window.location.href),t=[...s];t.length>0?e.searchParams.set(o,t.join(`,`)):e.searchParams.delete(o),e.searchParams.delete(`hasMedia`),e.searchParams.delete(`page`),window.location.href=e.pathname+(e.search||``)}};t.addEventListener(`click`,e=>{e.target.closest(`.archive-chip-clear`)||(t.getAttribute(`aria-expanded`)===`true`?u():l())}),document.addEventListener(`click`,t=>{e.contains(t.target)||u(!1)}),document.addEventListener(`basecoat:popover`,t=>{t.detail.source!==e&&u(!1)}),r.addEventListener(`click`,e=>{let t=e.target.closest(`[role="option"]`);if(t){if(t.dataset.navigate){let e=t.dataset.value;typeof e==`string`&&e.startsWith(`/`)&&(window.location.href=e);return}if(a){let e=t.dataset.value;s.has(e)?(s.delete(e),t.removeAttribute(`aria-selected`)):(s.add(e),t.setAttribute(`aria-selected`,`true`))}else{let e=t.dataset.value;typeof e==`string`&&e.startsWith(`/`)&&(window.location.href=e)}}});let d=-1,f=e=>{d>-1&&i[d]&&i[d].classList.remove(`active`),d=e,d>-1&&i[d]&&(i[d].classList.add(`active`),i[d].scrollIntoView({block:`nearest`}))};r.addEventListener(`mousemove`,e=>{let t=e.target.closest(`[role="option"]`);if(t){let e=i.indexOf(t);e!==-1&&e!==d&&f(e)}}),r.addEventListener(`mouseleave`,()=>{f(-1)}),t.addEventListener(`keydown`,e=>{let t=n.getAttribute(`aria-hidden`)===`false`;if(e.key===`Escape`){t&&(e.preventDefault(),u());return}if(!t&&[`ArrowDown`,`ArrowUp`].includes(e.key)){e.preventDefault(),l();return}t&&(e.preventDefault(),e.key===`ArrowDown`?f(Math.min(d+1,i.length-1)):e.key===`ArrowUp`?f(Math.max(d-1,0)):e.key===`Enter`&&d>-1&&(i[d].click(),!a&&!i[d].dataset.navigate&&u()))})});function bn(e=document){e.querySelectorAll(`.collection-sort-menu`).forEach(e=>{if(e.dataset.collectionSortMenuInitialized===`true`)return;let t=e.querySelector(`:scope > .collection-sort-trigger`),n=e.querySelector(`:scope > [data-popover]`),r=n?.querySelector(`[data-collection-sort-options]`);if(!(t instanceof HTMLButtonElement)||!n||!r)return;let i=(e=!1)=>{n.getAttribute(`aria-hidden`)!==`true`&&(n.setAttribute(`aria-hidden`,`true`),t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},a=()=>{document.dispatchEvent(new CustomEvent(`basecoat:popover`,{detail:{source:e}})),n.setAttribute(`aria-hidden`,`false`),t.setAttribute(`aria-expanded`,`true`)};t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),t.getAttribute(`aria-expanded`)===`true`?i(!1):a()}),t.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),i(!0);return}if(e.key===`ArrowDown`){e.preventDefault(),t.getAttribute(`aria-expanded`)!==`true`&&a();let n=r.querySelector(`a[href]`);n instanceof HTMLElement&&n.focus()}}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),i(!0))}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||i(!1))}),document.addEventListener(`basecoat:popover`,t=>{t.detail?.source!==e&&i(!1)}),e.dataset.collectionSortMenuInitialized=`true`})}bn(),r(),document.documentElement.dataset.jantVersion=`0.8.1-e6cbb5ae6bfbb200`;
295
+ `:t}};customElements.define(`jant-text-preview`,gn);function _n(e){return e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey}function vn(e,t){t&&(e.textContent=t)}function yn(e){let t=e.target;if(!(t instanceof globalThis.Element))return;let n=t.closest(`a[data-note-expand]`);if(!n||_n(e))return;let r=n.closest(`article[data-post]`),i=r?.querySelector(`[data-post-body]`);if(r&&i&&i.querySelector(`[data-note-break]`)){if(e.preventDefault(),i.hasAttribute(`data-note-clamp`)){i.removeAttribute(`data-note-clamp`),n.setAttribute(`aria-expanded`,`true`),vn(n,n.dataset.labelLess);return}i.setAttribute(`data-note-clamp`,``),n.setAttribute(`aria-expanded`,`false`),vn(n,n.dataset.labelMore),r.getBoundingClientRect().top<0&&typeof r.scrollIntoView==`function`&&r.scrollIntoView({block:`start`})}}document.addEventListener(`click`,yn),document.querySelectorAll(`.archive-chip-dropdown`).forEach(e=>{let t=e.querySelector(`:scope > button`),n=e.querySelector(`:scope > [data-popover]`),r=n?n.querySelector(`[role="listbox"]`):null;if(!t||!n||!r)return;let i=Array.from(r.querySelectorAll(`[role="option"]`)),a=e.classList.contains(`archive-chip-media`),o=e.dataset.filterKey,s=new Set;a&&i.forEach(e=>{!e.dataset.navigate&&e.getAttribute(`aria-selected`)===`true`&&s.add(e.dataset.value)});let c=new Set(s),l=()=>{document.dispatchEvent(new CustomEvent(`basecoat:popover`,{detail:{source:e}})),n.setAttribute(`aria-hidden`,`false`),t.setAttribute(`aria-expanded`,`true`),a&&(c=new Set(s))},u=(e=!0)=>{if(n.getAttribute(`aria-hidden`)!==`true`&&(n.setAttribute(`aria-hidden`,`true`),t.setAttribute(`aria-expanded`,`false`),e&&t.focus(),a&&o&&(s.size!==c.size||[...s].some(e=>!c.has(e))))){let e=new URL(window.location.href),t=[...s];t.length>0?e.searchParams.set(o,t.join(`,`)):e.searchParams.delete(o),e.searchParams.delete(`hasMedia`),e.searchParams.delete(`page`),window.location.href=e.pathname+(e.search||``)}};t.addEventListener(`click`,e=>{e.target.closest(`.archive-chip-clear`)||(t.getAttribute(`aria-expanded`)===`true`?u():l())}),document.addEventListener(`click`,t=>{e.contains(t.target)||u(!1)}),document.addEventListener(`basecoat:popover`,t=>{t.detail.source!==e&&u(!1)}),r.addEventListener(`click`,e=>{let t=e.target.closest(`[role="option"]`);if(t){if(t.dataset.navigate){let e=t.dataset.value;typeof e==`string`&&e.startsWith(`/`)&&(window.location.href=e);return}if(a){let e=t.dataset.value;s.has(e)?(s.delete(e),t.removeAttribute(`aria-selected`)):(s.add(e),t.setAttribute(`aria-selected`,`true`))}else{let e=t.dataset.value;typeof e==`string`&&e.startsWith(`/`)&&(window.location.href=e)}}});let d=-1,f=e=>{d>-1&&i[d]&&i[d].classList.remove(`active`),d=e,d>-1&&i[d]&&(i[d].classList.add(`active`),i[d].scrollIntoView({block:`nearest`}))};r.addEventListener(`mousemove`,e=>{let t=e.target.closest(`[role="option"]`);if(t){let e=i.indexOf(t);e!==-1&&e!==d&&f(e)}}),r.addEventListener(`mouseleave`,()=>{f(-1)}),t.addEventListener(`keydown`,e=>{let t=n.getAttribute(`aria-hidden`)===`false`;if(e.key===`Escape`){t&&(e.preventDefault(),u());return}if(!t&&[`ArrowDown`,`ArrowUp`].includes(e.key)){e.preventDefault(),l();return}t&&(e.preventDefault(),e.key===`ArrowDown`?f(Math.min(d+1,i.length-1)):e.key===`ArrowUp`?f(Math.max(d-1,0)):e.key===`Enter`&&d>-1&&(i[d].click(),!a&&!i[d].dataset.navigate&&u()))})});function bn(e=document){e.querySelectorAll(`.collection-sort-menu`).forEach(e=>{if(e.dataset.collectionSortMenuInitialized===`true`)return;let t=e.querySelector(`:scope > .collection-sort-trigger`),n=e.querySelector(`:scope > [data-popover]`),r=n?.querySelector(`[data-collection-sort-options]`);if(!(t instanceof HTMLButtonElement)||!n||!r)return;let i=(e=!1)=>{n.getAttribute(`aria-hidden`)!==`true`&&(n.setAttribute(`aria-hidden`,`true`),t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},a=()=>{document.dispatchEvent(new CustomEvent(`basecoat:popover`,{detail:{source:e}})),n.setAttribute(`aria-hidden`,`false`),t.setAttribute(`aria-expanded`,`true`)};t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),t.getAttribute(`aria-expanded`)===`true`?i(!1):a()}),t.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),i(!0);return}if(e.key===`ArrowDown`){e.preventDefault(),t.getAttribute(`aria-expanded`)!==`true`&&a();let n=r.querySelector(`a[href]`);n instanceof HTMLElement&&n.focus()}}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),i(!0))}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||i(!1))}),document.addEventListener(`basecoat:popover`,t=>{t.detail?.source!==e&&i(!1)}),e.dataset.collectionSortMenuInitialized=`true`})}bn(),r(),document.documentElement.dataset.jantVersion=`0.9.0-f5f1d977f9cb3f8e`;
@@ -1,4 +1,4 @@
1
- import{T as e,g as t,h as n,i as r,m as i,n as a,t as o,u as s,x as ee,y as te}from"./chunks/lit-DW8VmJAT.js";import"./client-BT6kpcuG.js";import{n as c,t as ne}from"./chunks/confirm-D7GrwsCN.js";import{_ as l,a as re,d as u,f as d,g as f,h as p,i as ie,l as m,m as ae,n as oe,p as se,r as ce,t as h,u as g,v as _,y as le}from"./chunks/unsafe-svg-BkscJx69.js";import{r as v}from"./chunks/slug-format-CRXO1AL5.js";import{h as y,l as ue,u as b}from"./chunks/types-D5iF3H1a.js";import{t as de}from"./chunks/settings-paths-BcdySNx6.js";var x=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,fe=`M4 4 20 20`,pe=200,me=class extends o{static properties={_open:{state:!0},_query:{state:!0},_items:{state:!0},_note:{state:!0},_loading:{state:!0},_searched:{state:!0}};#e=null;#t=null;#n=0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1}disconnectedCallback(){super.disconnectedCallback();let e=this.#e;this.#e=null,e?.resolve(null)}pick(e){return this.#e?.resolve(null),this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1,this._open=!0,new Promise(t=>{this.#e={...e,resolve:t},this.updateComplete.then(()=>{let e=this.querySelector(`.picker-dialog`);e&&!e.open&&e.showModal(),this.querySelector(`.picker-dialog-input`)?.focus()})})}#r(e){this.#t&&clearTimeout(this.#t),this.#t=null,this.#n+=1;let t=this.querySelector(`.picker-dialog`);t?.open&&t.close();let n=this.#e;this.#e=null,this._open=!1,n?.resolve(e)}#i(e){let t=this.#e;if(!t)return;let n=e.target.value;this._query=n,this.#t&&clearTimeout(this.#t);let r=t.minQueryLength??2;if(n.trim().length<r){this.#n+=1,this._items=[],this._note=``,this._loading=!1,this._searched=!1;return}this._loading=!0,this.#t=setTimeout(()=>{this.#a(n,t)},pe)}async#a(e,t){let n=++this.#n;try{let r=await t.search(e);if(n!==this.#n)return;this._items=r.items,this._note=r.note??``}catch{if(n!==this.#n)return;this._items=[],this._note=``}finally{n===this.#n&&(this._loading=!1,this._searched=!0)}}#o(e){if(e.key===`Escape`){e.preventDefault(),this.#r(null);return}if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;let t=Array.from(this.querySelectorAll(`.picker-dialog-option`));if(t.length===0)return;e.preventDefault();let n=document.activeElement,r=t.findIndex(e=>e===n),i=e.key===`ArrowDown`?r<0?0:Math.min(r+1,t.length-1):r<=0?-1:r-1;if(i<0){this.querySelector(`.picker-dialog-input`)?.focus();return}t[i]?.focus()}#s(e){e.target===e.currentTarget&&this.#r(null)}render(){let e=this.#e;if(!this._open||!e)return a;let t=e.minQueryLength??2,n=this._query.trim().length<t;return r`
1
+ import{T as e,g as t,h as n,i as r,m as i,n as a,t as o,u as s,x as ee,y as te}from"./chunks/lit-DW8VmJAT.js";import"./client-S8oryJ0m.js";import{n as c,t as ne}from"./chunks/confirm-D7GrwsCN.js";import{_ as l,a as re,d as u,f as d,g as f,h as p,i as ie,l as m,m as ae,n as oe,p as se,r as ce,t as h,u as g,v as _,y as le}from"./chunks/unsafe-svg-BkscJx69.js";import{r as v}from"./chunks/slug-format-CRXO1AL5.js";import{h as y,l as ue,u as b}from"./chunks/types-D5iF3H1a.js";import{t as de}from"./chunks/settings-paths-BcdySNx6.js";var x=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,fe=`M4 4 20 20`,pe=200,me=class extends o{static properties={_open:{state:!0},_query:{state:!0},_items:{state:!0},_note:{state:!0},_loading:{state:!0},_searched:{state:!0}};#e=null;#t=null;#n=0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1}disconnectedCallback(){super.disconnectedCallback();let e=this.#e;this.#e=null,e?.resolve(null)}pick(e){return this.#e?.resolve(null),this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1,this._open=!0,new Promise(t=>{this.#e={...e,resolve:t},this.updateComplete.then(()=>{let e=this.querySelector(`.picker-dialog`);e&&!e.open&&e.showModal(),this.querySelector(`.picker-dialog-input`)?.focus()})})}#r(e){this.#t&&clearTimeout(this.#t),this.#t=null,this.#n+=1;let t=this.querySelector(`.picker-dialog`);t?.open&&t.close();let n=this.#e;this.#e=null,this._open=!1,n?.resolve(e)}#i(e){let t=this.#e;if(!t)return;let n=e.target.value;this._query=n,this.#t&&clearTimeout(this.#t);let r=t.minQueryLength??2;if(n.trim().length<r){this.#n+=1,this._items=[],this._note=``,this._loading=!1,this._searched=!1;return}this._loading=!0,this.#t=setTimeout(()=>{this.#a(n,t)},pe)}async#a(e,t){let n=++this.#n;try{let r=await t.search(e);if(n!==this.#n)return;this._items=r.items,this._note=r.note??``}catch{if(n!==this.#n)return;this._items=[],this._note=``}finally{n===this.#n&&(this._loading=!1,this._searched=!0)}}#o(e){if(e.key===`Escape`){e.preventDefault(),this.#r(null);return}if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;let t=Array.from(this.querySelectorAll(`.picker-dialog-option`));if(t.length===0)return;e.preventDefault();let n=document.activeElement,r=t.findIndex(e=>e===n),i=e.key===`ArrowDown`?r<0?0:Math.min(r+1,t.length-1):r<=0?-1:r-1;if(i<0){this.querySelector(`.picker-dialog-input`)?.focus();return}t[i]?.focus()}#s(e){e.target===e.currentTarget&&this.#r(null)}render(){let e=this.#e;if(!this._open||!e)return a;let t=e.minQueryLength??2,n=this._query.trim().length<t;return r`
2
2
  <dialog
3
3
  class="dialog picker-dialog"
4
4
  @cancel=${e=>{e.preventDefault(),this.#r(null)}}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { n as createApp } from "./app--uxnaIRV.js";
1
+ import { n as createApp } from "./app-BzH8jmh3.js";
2
2
  export { createApp };
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as BUILTIN_FONT_THEMES, C as getEnvString, D as getTelegramBotPool, E as getSiteResolutionMode, F as BUILTIN_COLOR_THEMES, I as getPublicAssetBasePath, L as isAssetPath, M as getFontThemeCssVariables, N as resolveCjkFontProfile, O as getTelegramWebhookSecret, P as buildThemeStyle, S as getConfiguredStorageDriver, T as getPort, _ as createNodeDatabase, a as setUpNodeInstance, b as getConfiguredSingleSiteOrigin, c as resolveDatabaseDialect, d as getWebhookUrl, f as setMyCommands, g as sqliteSchemaBundle, h as pgSchemaBundle, i as createNodeRequestRuntime, j as getCjkFontCssVariables, k as shouldTrustProxy, l as createExportService, m as createStorageDriver, n as createApp, o as createSiteService, p as setWebhook, r as createNodeCliRuntime, s as getHostBasedStartupConfigurationIssues, u as resolveConfig, v as schema_exports, w as getHostedControlPlaneBaseUrl, x as getConfiguredSingleSitePathPrefix, y as now } from "./app--uxnaIRV.js";
1
+ import { A as BUILTIN_FONT_THEMES, C as getEnvString, D as getTelegramBotPool, E as getSiteResolutionMode, F as BUILTIN_COLOR_THEMES, I as getPublicAssetBasePath, L as isAssetPath, M as getFontThemeCssVariables, N as resolveCjkFontProfile, O as getTelegramWebhookSecret, P as buildThemeStyle, S as getConfiguredStorageDriver, T as getPort, _ as createNodeDatabase, a as setUpNodeInstance, b as getConfiguredSingleSiteOrigin, c as resolveDatabaseDialect, d as getWebhookUrl, f as setMyCommands, g as sqliteSchemaBundle, h as pgSchemaBundle, i as createNodeRequestRuntime, j as getCjkFontCssVariables, k as shouldTrustProxy, l as createExportService, m as createStorageDriver, n as createApp, o as createSiteService, p as setWebhook, r as createNodeCliRuntime, s as getHostBasedStartupConfigurationIssues, u as resolveConfig, v as schema_exports, w as getHostedControlPlaneBaseUrl, x as getConfiguredSingleSitePathPrefix, y as now } from "./app-BzH8jmh3.js";
2
2
  import { drizzle } from "drizzle-orm/better-sqlite3";
3
3
  import { serve } from "@hono/node-server";
4
4
  import Database from "better-sqlite3";
@@ -530,7 +530,7 @@ async function createNodeRequestHandler(options) {
530
530
  async function start(env = process.env, app) {
531
531
  const handler = await createNodeRequestHandler({
532
532
  env,
533
- app: async () => app ?? (await import("./app--uxnaIRV.js").then((n) => n.t)).createApp()
533
+ app: async () => app ?? (await import("./app-BzH8jmh3.js").then((n) => n.t)).createApp()
534
534
  });
535
535
  const hostname = resolveHost(env);
536
536
  const port = resolvePort(env);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jant/core",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "A modern, open-source microblogging platform built on Cloudflare Workers",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Cursor Walk Helper
3
3
  *
4
- * Follows a paginated posts endpoint the way a client does, so route tests can
5
- * compare a walk against one unpaged request.
4
+ * Follows a paginated posts or Threads endpoint the way a client does, so route
5
+ * tests can compare a walk against one unpaged request.
6
6
  */
7
7
 
8
8
  import { expect } from "vitest";
@@ -30,6 +30,36 @@ export async function walkPostPages(
30
30
  path: string,
31
31
  limit: number,
32
32
  from: string | null = null,
33
+ ): Promise<string[]> {
34
+ return walkPages(app, path, limit, "posts", from);
35
+ }
36
+
37
+ /**
38
+ * {@link walkPostPages} for a Thread list, whose pages hold `threads`.
39
+ *
40
+ * @param app - The test app the endpoint is mounted on
41
+ * @param path - Endpoint path with its query, without `limit` or `cursor`
42
+ * @param limit - Page size
43
+ * @returns Every Thread ID, in the order the pages returned them
44
+ * @example
45
+ * ```ts
46
+ * expect(await walkThreadPages(app, "/api/public/threads", 1)).toEqual(ids);
47
+ * ```
48
+ */
49
+ export async function walkThreadPages(
50
+ app: RequestTarget,
51
+ path: string,
52
+ limit: number,
53
+ ): Promise<string[]> {
54
+ return walkPages(app, path, limit, "threads", null);
55
+ }
56
+
57
+ async function walkPages(
58
+ app: RequestTarget,
59
+ path: string,
60
+ limit: number,
61
+ key: "posts" | "threads",
62
+ from: string | null,
33
63
  ): Promise<string[]> {
34
64
  const separator = path.includes("?") ? "&" : "?";
35
65
  const ids: string[] = [];
@@ -40,11 +70,11 @@ export async function walkPostPages(
40
70
  : `limit=${limit}`;
41
71
  const res = await app.request(`${path}${separator}${query}`);
42
72
  expect(res.status).toBe(200);
43
- const body = (await res.json()) as {
44
- posts: Array<{ id: string }>;
45
- nextCursor: string | null;
46
- };
47
- ids.push(...body.posts.map((post) => post.id));
73
+ const body = (await res.json()) as Record<
74
+ typeof key,
75
+ Array<{ id: string }>
76
+ > & { nextCursor: string | null };
77
+ ids.push(...body[key].map((item) => item.id));
48
78
  if (body.nextCursor === null) return ids;
49
79
  cursor = body.nextCursor;
50
80
  }
package/src/app.tsx CHANGED
@@ -36,6 +36,7 @@ import { customUrlsRoutes } from "./routes/dash/custom-urls.js";
36
36
 
37
37
  // Routes - API
38
38
  import { postsApiRoutes } from "./routes/api/posts.js";
39
+ import { threadsApiRoutes } from "./routes/api/threads.js";
39
40
  import { attachmentsApiRoutes } from "./routes/api/attachments.js";
40
41
  import { navItemsApiRoutes } from "./routes/api/nav-items.js";
41
42
  import { collectionsApiRoutes } from "./routes/api/collections.js";
@@ -60,6 +61,7 @@ import { internalPostBodyHtmlRoutes } from "./routes/api/internal/post-body-html
60
61
  import { internalUploadsRoutes } from "./routes/api/internal/uploads.js";
61
62
  import { publicArchiveApiRoutes } from "./routes/api/public/archive.js";
62
63
  import { publicPostsApiRoutes } from "./routes/api/public/posts.js";
64
+ import { publicThreadsApiRoutes } from "./routes/api/public/threads.js";
63
65
  import { discoverApiRoutes } from "./routes/api/discover.js";
64
66
  // Routes - Compose
65
67
  import { composeRoutes } from "./routes/compose.js";
@@ -579,9 +581,11 @@ export function createApp(): App {
579
581
 
580
582
  // API Routes
581
583
  app.route("/api/public/posts", publicPostsApiRoutes);
584
+ app.route("/api/public/threads", publicThreadsApiRoutes);
582
585
  app.route("/api/public/archive", publicArchiveApiRoutes);
583
586
  app.route("/api/discover", discoverApiRoutes);
584
587
  app.route("/api/posts", postsApiRoutes);
588
+ app.route("/api/threads", threadsApiRoutes);
585
589
  app.route("/api/nav-items", navItemsApiRoutes);
586
590
  app.route("/api/collections", collectionsApiRoutes);
587
591
  app.route("/api/smart-collections", smartCollectionsApiRoutes);
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
+ foldReplyWindows,
3
4
  foldThreadReplies,
4
5
  getThreadHiddenCount,
5
6
  THREAD_LEADING_REPLIES,
@@ -73,6 +74,48 @@ describe("foldThreadReplies", () => {
73
74
  });
74
75
  });
75
76
 
77
+ describe("foldReplyWindows", () => {
78
+ /**
79
+ * The windows as `getThreadTimelineContext` ranks them in SQL: overlapping
80
+ * on a short thread, the trailing window without the hero, and the reply one
81
+ * past the leading window fetched whether or not it ends up hidden.
82
+ */
83
+ const rankedWindows = (count: number) => {
84
+ const all = replies(count);
85
+ return {
86
+ leadingReplies: all.slice(0, THREAD_LEADING_REPLIES),
87
+ trailingReplies: all.slice(
88
+ Math.max(0, count - THREAD_TRAILING_REPLIES),
89
+ count - 1,
90
+ ),
91
+ latestReply: all[count - 1] ?? reply(0),
92
+ nextReply: all[THREAD_LEADING_REPLIES] ?? null,
93
+ totalReplyCount: count,
94
+ };
95
+ };
96
+
97
+ // The site and the API fold from ranked windows, the feed from the whole
98
+ // chain. Both must describe the same thread the same way.
99
+ it.each([1, 2, 3, 4, 5, 6, 7, 12])(
100
+ "folds %i replies the way the whole chain does",
101
+ (count) => {
102
+ expect(foldReplyWindows(rankedWindows(count))).toEqual(
103
+ foldThreadReplies(replies(count)),
104
+ );
105
+ },
106
+ );
107
+
108
+ // With four replies the reply after the leading window is the third-newest,
109
+ // on screen in the trailing window. It is not a gap target.
110
+ it("never points the gap at a reply it shows", () => {
111
+ const fold = foldReplyWindows(rankedWindows(4));
112
+
113
+ expect(fold.hiddenCount).toBe(0);
114
+ expect(fold.firstHiddenReply).toBeNull();
115
+ expect(ids(fold.trailingReplies)).toEqual(["reply-3"]);
116
+ });
117
+ });
118
+
76
119
  describe("getThreadHiddenCount", () => {
77
120
  // The site selects its buckets in SQL and they overlap on short threads, so
78
121
  // the count has to dedupe rather than subtract two lengths.
@@ -1,5 +1,8 @@
1
1
  import { isTextAttachment } from "../services/media.js";
2
- import type { Media, Post } from "../types.js";
2
+ import type { Services } from "../services/index.js";
3
+ import type { PostFilters } from "../services/post.js";
4
+ import type { AppConfig } from "../types/config.js";
5
+ import type { Media, Post, Status } from "../types.js";
3
6
  import { getPostDisplayTitle } from "./post-meta.js";
4
7
  import { getImageUrl, getMediaUrl, getPublicUrlForProvider } from "./image.js";
5
8
  import { toPublicPath } from "./url.js";
@@ -14,11 +17,37 @@ export type ApiPostResponse = Omit<Post, "title" | "url"> & {
14
17
  * a URL, not a name.
15
18
  */
16
19
  displayTitle: string;
20
+ /**
21
+ * Published Posts in this Post's Thread, its root included: 1 for a Post on
22
+ * its own, 0 while nothing in the Thread is published.
23
+ */
24
+ threadPostCount: number;
17
25
  url?: string | null;
18
26
  sourceName?: string | null;
19
27
  sourceUrl?: string | null;
20
28
  };
21
29
 
30
+ /**
31
+ * The order `GET /api/posts` and `jant_posts_list` walk Posts in.
32
+ *
33
+ * Published Posts run newest-published first, pins ignored: a Post's place
34
+ * then depends on its own publication alone, and a reply added to an old
35
+ * Thread doesn't lift the root past a walk's cursor. Drafts keep the editing
36
+ * order the composer's draft list reads, last edited first.
37
+ *
38
+ * @param status - The status the list is filtered to
39
+ * @returns The `PostFilters` ordering fields for that list
40
+ * @example
41
+ * posts.listPage({ status, ...apiPostListOrder(status) }, { limit: 100 });
42
+ */
43
+ export function apiPostListOrder(
44
+ status: Status,
45
+ ): Pick<PostFilters, "sortBy" | "ignorePinnedSort"> {
46
+ return status === "draft"
47
+ ? {}
48
+ : { sortBy: "published", ignorePinnedSort: true };
49
+ }
50
+
22
51
  export function toApiAttachment(
23
52
  media: Media,
24
53
  r2PublicUrl?: string,
@@ -84,9 +113,10 @@ export function toApiAttachment(
84
113
  export function toApiPost(
85
114
  post: Post,
86
115
  extras: {
116
+ threadPostCount: number;
87
117
  attachments?: ReturnType<typeof toApiAttachment>[];
88
118
  collectionIds?: string[];
89
- } = {},
119
+ },
90
120
  ): ApiPostResponse {
91
121
  const { title, url, ...rest } = post;
92
122
  // A short name for this Post wherever it is referenced from somewhere else —
@@ -111,3 +141,81 @@ export function toApiPost(
111
141
  url: url ?? null,
112
142
  };
113
143
  }
144
+
145
+ /** What {@link loadApiPostResponses} reads through. */
146
+ export interface ApiPostResponseDeps {
147
+ services: Pick<Services, "media" | "posts" | "collections">;
148
+ appConfig: AppConfig;
149
+ }
150
+
151
+ /**
152
+ * API responses for Posts already loaded. Attachments, Thread Post counts,
153
+ * and (when asked) Thread collections are each read in one batch for the
154
+ * whole set, so a page costs the same few round trips however long it is.
155
+ *
156
+ * @param deps - Services and app config; a request's `c.var` or an MCP context
157
+ * @param posts - Posts to respond with, in order
158
+ * @param options - `collectionIds` adds each Post's shared Thread collections
159
+ * @returns One response per Post, in the same order
160
+ * @example
161
+ * const responses = await loadApiPostResponses(c.var, page.posts);
162
+ */
163
+ export async function loadApiPostResponses(
164
+ deps: ApiPostResponseDeps,
165
+ posts: Post[],
166
+ options: { collectionIds?: boolean } = {},
167
+ ): Promise<ApiPostResponse[]> {
168
+ if (posts.length === 0) return [];
169
+ const { services, appConfig } = deps;
170
+ const postIds = posts.map((post) => post.id);
171
+ const [mediaMap, threadPostCounts, collectionsMap] = await Promise.all([
172
+ services.media.getByPostIds(postIds),
173
+ services.posts.countThreadPosts(posts.map((post) => post.threadId)),
174
+ options.collectionIds
175
+ ? services.collections.getCollectionsByPostIds(postIds)
176
+ : Promise.resolve(null),
177
+ ]);
178
+
179
+ return posts.map((post) =>
180
+ toApiPost(post, {
181
+ threadPostCount: threadPostCounts.get(post.threadId) ?? 0,
182
+ attachments: (mediaMap.get(post.id) ?? []).map((media) =>
183
+ toApiAttachment(
184
+ media,
185
+ appConfig.r2PublicUrl,
186
+ appConfig.imageTransformUrl,
187
+ appConfig.s3PublicUrl,
188
+ appConfig.localPublicUrl,
189
+ appConfig.sitePathPrefix,
190
+ ),
191
+ ),
192
+ ...(collectionsMap
193
+ ? {
194
+ collectionIds: (collectionsMap.get(post.id) ?? []).map(
195
+ (collection) => collection.id,
196
+ ),
197
+ }
198
+ : {}),
199
+ }),
200
+ );
201
+ }
202
+
203
+ /**
204
+ * One Post's API response. See {@link loadApiPostResponses}.
205
+ *
206
+ * @param deps - Services and app config
207
+ * @param post - The Post
208
+ * @param options - `collectionIds` adds the Post's shared Thread collections
209
+ * @returns The Post's response
210
+ * @example
211
+ * return c.json(await loadApiPostResponse(c.var, post));
212
+ */
213
+ export async function loadApiPostResponse(
214
+ deps: ApiPostResponseDeps,
215
+ post: Post,
216
+ options: { collectionIds?: boolean } = {},
217
+ ): Promise<ApiPostResponse> {
218
+ const [response] = await loadApiPostResponses(deps, [post], options);
219
+ if (!response) throw new Error(`No response built for post ${post.id}`);
220
+ return response;
221
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Public API Post responses
3
+ *
4
+ * The reading view of a Post that `/api/public/*` returns: rendered body or
5
+ * Markdown, public permalink, and public collection references.
6
+ */
7
+
8
+ import type { Services } from "../services/index.js";
9
+ import type { AppConfig } from "../types/config.js";
10
+ import type { Collection, Media, Post } from "../types.js";
11
+ import { getCollectionPagePath } from "./collection-paths.js";
12
+ import { toApiAttachment } from "./api-posts.js";
13
+ import { tiptapJsonToMarkdown } from "./tiptap-to-markdown.js";
14
+ import { toPublicPath } from "./url.js";
15
+ import { getImageUrl, getMediaUrl, getPublicUrlForProvider } from "./image.js";
16
+
17
+ export type PublicPostBaseResponse = {
18
+ id: string;
19
+ format: Post["format"];
20
+ status: "published";
21
+ visibility: Post["visibility"];
22
+ slug: string;
23
+ permalink: string;
24
+ title?: string | null;
25
+ url?: string | null;
26
+ sourceName?: string | null;
27
+ sourceUrl?: string | null;
28
+ quoteText: string | null;
29
+ summary: string | null;
30
+ rating: number | null;
31
+ previewKind: string | null;
32
+ previewProvider: string | null;
33
+ previewImageUrl: string | null;
34
+ replyToId: string | null;
35
+ threadId: string;
36
+ /**
37
+ * BCP 47 content language, or null on a post written before the site
38
+ * enabled multilingual content.
39
+ */
40
+ language: string | null;
41
+ /**
42
+ * Shared by every translation of this Thread. Null when the Thread has no
43
+ * translations.
44
+ */
45
+ translationGroupId: string | null;
46
+ /** Reply published without announcing its Thread. Always false on roots. */
47
+ quietReply: boolean;
48
+ pinnedAt: number | null;
49
+ featuredAt: number | null;
50
+ publishedAt: number | null;
51
+ /** Root only: newest post in the Thread, quiet replies excluded. */
52
+ lastActivityAt: number;
53
+ /** Root only: newest post in the Thread, quiet replies included. */
54
+ threadUpdatedAt: number;
55
+ /**
56
+ * Published Posts in this Post's Thread, its root included: 1 for a Post on
57
+ * its own.
58
+ */
59
+ threadPostCount: number;
60
+ createdAt: number;
61
+ updatedAt: number;
62
+ attachments: ReturnType<typeof toApiAttachment>[];
63
+ collections: {
64
+ id: string;
65
+ slug: string;
66
+ title: string;
67
+ url: string;
68
+ }[];
69
+ };
70
+
71
+ export type PublicPostRenderedResponse = PublicPostBaseResponse & {
72
+ bodyHtml: string | null;
73
+ bodyText: string | null;
74
+ };
75
+
76
+ export type PublicPostMarkdownResponse = PublicPostBaseResponse & {
77
+ bodyMarkdown: string | null;
78
+ };
79
+
80
+ export type PublicPostResponse =
81
+ PublicPostRenderedResponse | PublicPostMarkdownResponse;
82
+
83
+ /**
84
+ * The public Markdown for a post, or null for a historical body that isn't
85
+ * TipTap JSON. One unreadable row answers null and is logged, rather than
86
+ * failing the whole listing; `bodyHtml` still falls back to stored HTML.
87
+ */
88
+ function toPublicBodyMarkdown(postId: string, body: string): string | null {
89
+ try {
90
+ return tiptapJsonToMarkdown(body);
91
+ } catch (error) {
92
+ // eslint-disable-next-line no-console -- A skipped body must leave a trace
93
+ console.error(
94
+ `Couldn't convert the body of post ${postId} to Markdown`,
95
+ error,
96
+ );
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * One Post's reading view, from its attachments, its Thread's collections, and
103
+ * its Thread's Post count.
104
+ *
105
+ * @param post - The Post
106
+ * @param related - What was read about it in the same batch as its page
107
+ * @param appConfig - Media URLs and the site path prefix
108
+ * @param options - `content: "markdown"` returns `bodyMarkdown` instead of the
109
+ * rendered body
110
+ * @returns The public response
111
+ * @example
112
+ * toPublicPost(post, { media: [], collections: [], threadPostCount: 1 }, config);
113
+ */
114
+ export function toPublicPost(
115
+ post: Post,
116
+ related: {
117
+ media: Media[];
118
+ collections: Collection[];
119
+ threadPostCount: number;
120
+ },
121
+ appConfig: AppConfig,
122
+ options?: { content?: "markdown" },
123
+ ): PublicPostResponse {
124
+ const {
125
+ r2PublicUrl,
126
+ imageTransformUrl,
127
+ s3PublicUrl,
128
+ localPublicUrl,
129
+ sitePathPrefix,
130
+ storageDriver,
131
+ } = appConfig;
132
+
133
+ const previewImagePublicUrl = getPublicUrlForProvider(
134
+ storageDriver,
135
+ r2PublicUrl,
136
+ s3PublicUrl,
137
+ localPublicUrl,
138
+ );
139
+ const previewImageUrl = post.previewImageKey
140
+ ? getImageUrl(
141
+ getMediaUrl(
142
+ post.previewImageKey,
143
+ previewImagePublicUrl,
144
+ sitePathPrefix,
145
+ ),
146
+ imageTransformUrl,
147
+ { width: 1280, quality: 80, format: "auto", fit: "scale-down" },
148
+ )
149
+ : null;
150
+
151
+ const base = {
152
+ id: post.id,
153
+ format: post.format,
154
+ status: "published" as const,
155
+ visibility: post.visibility,
156
+ slug: post.slug,
157
+ permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
158
+ quoteText: post.quoteText,
159
+ summary: post.summary,
160
+ rating: post.rating,
161
+ previewKind: post.previewKind,
162
+ previewProvider: post.previewProvider,
163
+ previewImageUrl,
164
+ replyToId: post.replyToId,
165
+ threadId: post.threadId,
166
+ language: post.language,
167
+ translationGroupId: post.translationGroupId,
168
+ quietReply: post.quietReply,
169
+ pinnedAt: post.pinnedAt,
170
+ featuredAt: post.featuredAt,
171
+ publishedAt: post.publishedAt,
172
+ lastActivityAt: post.lastActivityAt,
173
+ threadUpdatedAt: post.threadUpdatedAt,
174
+ threadPostCount: related.threadPostCount,
175
+ createdAt: post.createdAt,
176
+ updatedAt: post.updatedAt,
177
+ attachments: related.media.map((media) =>
178
+ toApiAttachment(
179
+ media,
180
+ r2PublicUrl,
181
+ imageTransformUrl,
182
+ s3PublicUrl,
183
+ localPublicUrl,
184
+ sitePathPrefix,
185
+ ),
186
+ ),
187
+ collections: related.collections.map((collection) => ({
188
+ id: collection.id,
189
+ slug: collection.slug,
190
+ title: collection.title,
191
+ url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix),
192
+ })),
193
+ };
194
+ const contentFields =
195
+ options?.content === "markdown"
196
+ ? {
197
+ bodyMarkdown: post.body
198
+ ? toPublicBodyMarkdown(post.id, post.body)
199
+ : null,
200
+ }
201
+ : {
202
+ bodyHtml: post.bodyHtml,
203
+ bodyText: post.bodyText,
204
+ };
205
+
206
+ if (post.format === "quote") {
207
+ return {
208
+ ...base,
209
+ ...contentFields,
210
+ sourceName: post.title,
211
+ sourceUrl: post.url,
212
+ };
213
+ }
214
+
215
+ return {
216
+ ...base,
217
+ ...contentFields,
218
+ title: post.title,
219
+ url: post.url,
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Reading-view responses for Posts already loaded. Attachments, Thread
225
+ * collections, and Thread Post counts are each read in one batch.
226
+ *
227
+ * @param deps - Services and app config; a request's `c.var`
228
+ * @param posts - Posts to respond with, in order
229
+ * @param options - `content: "markdown"` returns `bodyMarkdown`
230
+ * @returns One response per Post, in the same order
231
+ * @example
232
+ * const responses = await loadPublicPostResponses(c.var, page.posts, {});
233
+ */
234
+ export async function loadPublicPostResponses(
235
+ deps: {
236
+ services: Pick<Services, "media" | "posts" | "collections">;
237
+ appConfig: AppConfig;
238
+ },
239
+ posts: Post[],
240
+ options: { content?: "markdown" } = {},
241
+ ): Promise<PublicPostResponse[]> {
242
+ if (posts.length === 0) return [];
243
+ const { services, appConfig } = deps;
244
+ const postIds = posts.map((post) => post.id);
245
+ const [mediaMap, collectionsMap, threadPostCounts] = await Promise.all([
246
+ services.media.getByPostIds(postIds),
247
+ services.collections.getCollectionsByPostIds(postIds),
248
+ services.posts.countThreadPosts(posts.map((post) => post.threadId)),
249
+ ]);
250
+
251
+ return posts.map((post) =>
252
+ toPublicPost(
253
+ post,
254
+ {
255
+ media: mediaMap.get(post.id) ?? [],
256
+ collections: collectionsMap.get(post.id) ?? [],
257
+ threadPostCount: threadPostCounts.get(post.threadId) ?? 0,
258
+ },
259
+ appConfig,
260
+ options,
261
+ ),
262
+ );
263
+ }