From af70f720aab72f0845d52c8363bde682a357ee6c Mon Sep 17 00:00:00 2001 From: Thomas Jung Date: Sat, 21 Nov 2026 18:53:00 -0500 Subject: [PATCH 01/11] fix(search): exclude ROLE_GATED from public semantic_search (#3168, #3099 leak) --- .../lib/semantic-search-visibility.test.js | 127 ++++++++++++++++++ srv/lib/semantic-search.js | 9 +- 2 files changed, 134 insertions(+), 2 deletions(-) create mode 100644 srv/__tests__/lib/semantic-search-visibility.test.js diff --git a/srv/__tests__/lib/semantic-search-visibility.test.js b/srv/__tests__/lib/semantic-search-visibility.test.js new file mode 100644 index 000000000..88569ff4c --- /dev/null +++ b/srv/__tests__/lib/semantic-search-visibility.test.js @@ -0,0 +1,127 @@ +// srv/__tests__/lib/semantic-search-visibility.test.js +// +// TDD for Task 1: Fix public semantic_search ROLE_GATED leak (#3168, #3099). +// Tests that the public anonymous semantic tutorial corpus excludes ROLE_GATED +// tutorials even when they are ACTIVE and present in ContentCurrent. + +import cds from '@sap/cds'; +import { describe, it, expect, beforeAll, beforeEach } from 'vitest'; +import { gzipSync } from 'node:zlib'; +import { _setTestEmbedClient, _resetForTest, semanticSearch } from '../../lib/semantic-search.js'; + +const NS = 'com.sap.developers.ims'; + +cds.test('serve', '--project', '.', '--in-memory'); + +/** + * Seed a tutorial with an embedding and ContentCurrent entry. + * @param {string} slug - Tutorial slug + * @param {object} opts - { visibility: 'LISTED' | 'ROLE_GATED', model: 'text-embedding-3-small' } + */ +async function seedTutorialWithEmbedding(slug, { visibility = 'LISTED', model = 'text-embedding-3-small' } = {}) { + const NS_ENT = cds.entities(NS); + const { ContentManifest, ContentFiles, Tutorials, TutorialEmbedding, ContentCurrent, Steps } = NS_ENT; + + const tutorialId = cds.utils.uuid(); + const stepId = cds.utils.uuid(); + const html = `Content for ${slug}`; + + // Ensure we have an ACTIVE manifest. + const existing = await SELECT.one.from(ContentManifest).where({ status: 'ACTIVE' }); + if (!existing) { + await INSERT.into(ContentManifest).entries({ + version: 1, status: 'ACTIVE', activatedAt: new Date().toISOString(), + }); + } + + // Insert ContentFiles entry. + await INSERT.into(ContentFiles).entries({ + slug, version: 1, + content: gzipSync(Buffer.from(html)), + sourceContent: gzipSync(Buffer.from(`---\ntitle: ${slug}\n---\n`)), + contentHash: `hash-${slug}`, sourceHash: `src-${slug}`, + mimeType: 'text/html', sizeBytes: html.length, + }); + + // Insert Tutorial with specified visibility. + await INSERT.into(Tutorials).entries({ + ID: tutorialId, slug, title: slug, status: 'ACTIVE', visibility, + }); + + // Insert a Step for the tutorial (needed for embedding FK). + await INSERT.into(Steps).entries({ + ID: stepId, tutorial_ID: tutorialId, stepNumber: 1, duration: 5, title: `Step 1 of ${slug}`, + }); + + // Create a dummy embedding vector (1536 floats, all 0.1 for simplicity). + const dummyVec = new Float32Array(1536); + dummyVec.fill(0.1); + const vecBuffer = Buffer.alloc(dummyVec.length * 4); + for (let i = 0; i < dummyVec.length; i++) { + vecBuffer.writeFloatLE(dummyVec[i], i * 4); + } + + // Insert TutorialEmbedding. + await INSERT.into(TutorialEmbedding).entries({ + tutorial_ID: tutorialId, stepNumber: 1, + contentHash: `hash-${slug}`, + embeddingModel: model, + embedding: vecBuffer, + stepText: `${slug} step 1 content`, + charCount: `${slug} step 1 content`.length, + }); + + // Insert ContentCurrent entry to mark this slug as servable. + await INSERT.into(ContentCurrent).entries({ + slug, version: 1, mimeType: 'text/html', + content: gzipSync(Buffer.from(html)), + }); +} + +describe('semantic search visibility enforcement', () => { + beforeAll(async () => { + await cds.connect.to('db'); + }); + + beforeEach(async () => { + // Clear per-test to avoid slug collisions. + const { ContentManifest, ContentFiles, Tutorials, TutorialEmbedding, ContentCurrent, Steps } = cds.entities(NS); + await DELETE.from(TutorialEmbedding); + await DELETE.from(ContentCurrent); + await DELETE.from(ContentFiles); + await DELETE.from(ContentManifest); + await DELETE.from(Steps); + await DELETE.from(Tutorials); + + // Reset semantic-search module state. + await _resetForTest(); + }); + + it('public semantic search excludes ROLE_GATED tutorials', async () => { + const model = 'text-embedding-3-small'; + + // Seed two tutorials: one LISTED, one ROLE_GATED, both ACTIVE and in ContentCurrent. + await seedTutorialWithEmbedding('listed-tutorial', { visibility: 'LISTED', model }); + await seedTutorialWithEmbedding('pre-release-secret', { visibility: 'ROLE_GATED', model }); + + // Inject a fake embed fn that returns a reasonable query vector + // (same dummy vector as the embedded tutorials). + const queryVec = new Float32Array(1536); + queryVec.fill(0.1); + _setTestEmbedClient(async () => [queryVec]); + + // Call the public semantic search with corpus='tutorials' (the default). + const results = await semanticSearch({ + query: 'test query', + corpus: 'tutorials', + settings: { embeddingModel: model }, + }); + + const slugs = results.map(r => r.slug); + + // Pin as a true-positive probe: LISTED must be present (vacuous-pass guard), + // and ROLE_GATED must be absent. + expect(slugs).toContain('listed-tutorial'); + expect(slugs).not.toContain('pre-release-secret'); + }); +}); diff --git a/srv/lib/semantic-search.js b/srv/lib/semantic-search.js index 744cb4aaa..84c9d7f61 100644 --- a/srv/lib/semantic-search.js +++ b/srv/lib/semantic-search.js @@ -169,6 +169,8 @@ async function searchTutorials({ db, qVec, model, topK }) { // #2631: gate on Tutorials.status so soft-deleted (INACTIVE) tutorials — // whose embeddings survive the delete — never surface. Mirrors the public // predicate used by SearchableItems and the homepage shelves. + // #3168: also gate on Tutorials.visibility to exclude ROLE_GATED tutorials + // from public anonymous search (the semantic_search endpoint). const sql = ` SELECT TOP ${topK} e."STEPNUMBER", e."STEPTEXT", @@ -178,6 +180,7 @@ async function searchTutorials({ db, qVec, model, topK }) { JOIN "COM_SAP_DEVELOPERS_IMS_TUTORIALS" t ON t."ID" = e."TUTORIAL_ID" WHERE e."EMBEDDINGMODEL" = ? AND (t."STATUS" IS NULL OR t."STATUS" = 'ACTIVE') + AND (t."VISIBILITY" IS NULL OR t."VISIBILITY" <> 'ROLE_GATED') ORDER BY "score" DESC`; const rows = await db.run(sql, [hanaVecStr(qVec), model]); results = (rows || []).map((r) => shapeTutorial( @@ -185,14 +188,16 @@ async function searchTutorials({ db, qVec, model, topK }) { r.STEPNUMBER ?? r.stepNumber, r.STEPTEXT ?? r.stepText, r.score ?? r.SCORE)); } else { // SQLite: fetch model rows + tutorial index, rank in JS. The tutorial - // index is pre-filtered to ACTIVE/null so INACTIVE rows drop out of tMap. + // index is pre-filtered to ACTIVE/null and non-ROLE_GATED so INACTIVE and + // ROLE_GATED rows drop out of tMap. const { TutorialEmbedding, Tutorials } = cds.entities('com.sap.developers.ims'); const rows = await SELECT.from(TutorialEmbedding) .columns('tutorial_ID', 'stepNumber', 'stepText', 'embedding') .where({ embeddingModel: model }); const tIndex = await SELECT.from(Tutorials) .columns('ID', 'slug', 'title') - .where(`status is null or status = 'ACTIVE'`); + .where(`status is null or status = 'ACTIVE'`) + .where(`visibility is null or visibility <> 'ROLE_GATED'`); const tMap = new Map(tIndex.map((t) => [t.ID, t])); results = (rows || []).map((r) => { const v = decodeF32(r.embedding); From 7388b2d206616d750b6f4a2a3bfaa2e6ad739f9c Mon Sep 17 00:00:00 2001 From: Thomas Jung Date: Sat, 21 Nov 2026 19:03:57 -0500 Subject: [PATCH 02/11] feat(prerelease): live gated nav feed for ROLE_GATED tutorials (#3168) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extract `buildNavTutorials(slugSet, contentRows, {visibilityFilter})` from `navHandlerFallback` — shared helper used by both the public cold-start fallback and the new gated live feed. - Visibility filter: 'ROLE_GATED' keeps only ROLE_GATED tutorials; default public path excludes ROLE_GATED (defense-in-depth; hardens the fallback — hot path uses the baked __nav__ blob, unchanged). - Add `preReleaseNavHandler` — enumerates ContentCurrent/ContentFiles slugs, calls buildNavTutorials with ROLE_GATED filter, sets Cache-Control: private, no-store. Does NOT read/write the shared slug-keyed cache (#3099 cache-leak rule). - Export via _defaults + module re-exports in packages/content/content-store.js, and re-export from srv/lib/content-store.js shim. - Mount at GET /content/tutorials-prerelease/_nav in srv/server.js, registered BEFORE the *slug wildcard so `_nav` is not swallowed as a slug. - TDD: 3 tests in srv/__tests__/lib/prerelease-nav.test.js — RED first, then GREEN. All 135 tests pass (21 test files, no regressions). --- packages/content/content-store.js | 150 ++++++++++++++++---- srv/__tests__/lib/prerelease-nav.test.js | 170 +++++++++++++++++++++++ srv/lib/content-store.js | 1 + srv/server.js | 7 +- 4 files changed, 298 insertions(+), 30 deletions(-) create mode 100644 srv/__tests__/lib/prerelease-nav.test.js diff --git a/packages/content/content-store.js b/packages/content/content-store.js index 14612ad50..31c7785e7 100644 --- a/packages/content/content-store.js +++ b/packages/content/content-store.js @@ -1762,36 +1762,46 @@ export function createContentHandlers({ namespace = 'com.sap.developers.ims', ap // --- GET /content/nav --- - async function navHandlerFallback(req, res, activeVersion) { - const { ContentFiles, ContentCurrent, Tutorials, Steps, TutorialTags, Tags } = cds.entities(namespace); - - // Option B: enumerate ContentCurrent (no version) when the read flag is on — - // correct once fully seeded (task 4.3). Metadata-only, plain CQL on both DBs. - const contentRows = (isDeltaRead() && ContentCurrent) - ? await SELECT.from(ContentCurrent).columns('slug', 'sizeBytes') - : await SELECT.from(ContentFiles).where({ version: activeVersion }).columns('slug', 'sizeBytes'); - - const slugs = contentRows.filter(r => - r.slug !== '__nav__' && r.slug !== '__404__' && r.slug !== '__shell__' - ).map(r => r.slug); - if (slugs.length === 0) { - res.setHeader('Cache-Control', 'public, max-age=60'); - return res.json({ version: activeVersion, count: 0, tutorials: [] }); - } - - const sizeMap = Object.fromEntries(contentRows.map(r => [r.slug, r.sizeBytes])); + /** + * buildNavTutorials — shared assembly helper used by both navHandlerFallback + * (public cold-start path) and preReleaseNavHandler (gated live path). + * + * @param {Set} slugSet — slugs to include (from ContentCurrent / ContentFiles) + * @param {object[]} contentRows — raw rows from ContentCurrent/ContentFiles (slug, sizeBytes) + * @param {{ visibilityFilter?: 'ROLE_GATED' | 'public' }} opts + * visibilityFilter === 'ROLE_GATED' → keep only ROLE_GATED tutorials (the gated feed). + * otherwise (default / 'public') → keep LISTED-or-null, EXCLUDE ROLE_GATED. + * INACTIVE tutorials are always excluded regardless of filter. + * + * HANA packet-cap constraint: Tutorials is fetched UNBOUNDED and filtered in + * Node — never use `.where({slug:{in:[...]}})` with a large slug array here. + * See memory note: cqn-where-in-hana-packet-cap.md (#1063, #1103). + */ + async function buildNavTutorials(slugSet, contentRows, { visibilityFilter } = {}) { + const { Tutorials, Steps, TutorialTags, Tags } = cds.entities(namespace); + const isGatedFilter = visibilityFilter === 'ROLE_GATED'; - // Fetch tutorial metadata for published slugs (excluding INACTIVE — soft-deleted). - // On a full publish `slugs` is ~7,315 entries; a `.where({slug:{in:slugs}})` - // here would send one bound param per slug and blow HANA's packet cap - // (memory note: cqn-where-in-hana-packet-cap.md; same class as #1063 and - // #1103). Fetch Tutorials unbounded (~7,315 rows × ~8 short cols ≪ 5 MB) - // and filter into `slugSet` in Node. Single fetch also lets us classify - // ACTIVE vs INACTIVE in Node instead of running the second IN-query below. - const slugSet = new Set(slugs); + // Fetch Tutorials unbounded — see HANA packet-cap note above. + // Add `visibility` column so we can filter ROLE_GATED here in Node. const allTutRows = await SELECT.from(Tutorials) - .columns('ID', 'slug', 'title', 'description', 'primaryTag', 'experienceTag', 'averageTimeToComplete', 'status'); - const tutRows = allTutRows.filter(t => slugSet.has(t.slug) && t.status !== 'INACTIVE'); + .columns('ID', 'slug', 'title', 'description', 'primaryTag', 'experienceTag', 'averageTimeToComplete', 'status', 'visibility'); + + // Filter by slugSet, INACTIVE, and visibility in one pass. + const tutRows = allTutRows.filter(t => { + if (!slugSet.has(t.slug)) return false; + if (t.status === 'INACTIVE') return false; + if (isGatedFilter) { + // Gated feed: keep only ROLE_GATED tutorials. + return t.visibility === 'ROLE_GATED'; + } else { + // Public feed: keep LISTED-or-null, exclude ROLE_GATED. + // Defense-in-depth: hardens the cold-start fallback which previously had + // no visibility filter. The hot path (baked __nav__ blob) already excludes + // ROLE_GATED at build time — this change is a safety net for the fallback only. + return t.visibility !== 'ROLE_GATED'; + } + }); + const inactiveSlugs = new Set( allTutRows.filter(t => slugSet.has(t.slug) && t.status === 'INACTIVE').map(t => t.slug) ); @@ -1850,10 +1860,12 @@ export function createContentHandlers({ namespace = 'com.sap.developers.ims', ap } } + // Build result: iterate contentRows so order mirrors publish order. const tutorials = contentRows .filter(r => r.slug !== '__nav__' && r.slug !== '__404__' && - r.slug !== '__shell__' && !inactiveSlugs.has(r.slug) + r.slug !== '__shell__' && !inactiveSlugs.has(r.slug) && + tutMap[r.slug] // only slugs that passed the visibility filter ) .map(r => { const meta = tutMap[r.slug]; @@ -1871,10 +1883,88 @@ export function createContentHandlers({ namespace = 'com.sap.developers.ims', ap }; }); + return tutorials; + } + + async function navHandlerFallback(req, res, activeVersion) { + const { ContentFiles, ContentCurrent } = cds.entities(namespace); + + // Option B: enumerate ContentCurrent (no version) when the read flag is on — + // correct once fully seeded (task 4.3). Metadata-only, plain CQL on both DBs. + const contentRows = (isDeltaRead() && ContentCurrent) + ? await SELECT.from(ContentCurrent).columns('slug', 'sizeBytes') + : await SELECT.from(ContentFiles).where({ version: activeVersion }).columns('slug', 'sizeBytes'); + + const slugs = contentRows.filter(r => + r.slug !== '__nav__' && r.slug !== '__404__' && r.slug !== '__shell__' + ).map(r => r.slug); + if (slugs.length === 0) { + res.setHeader('Cache-Control', 'public, max-age=60'); + return res.json({ version: activeVersion, count: 0, tutorials: [] }); + } + + const slugSet = new Set(slugs); + // Public path: visibilityFilter defaults to 'public' — excludes ROLE_GATED. + // This hardens the cold-start fallback; the hot path (baked __nav__) already + // excludes ROLE_GATED at build time so this only affects the fallback. + const tutorials = await buildNavTutorials(slugSet, contentRows, { visibilityFilter: 'public' }); + res.setHeader('Cache-Control', 'public, max-age=60'); res.json({ version: activeVersion, count: tutorials.length, tutorials }); } + // --- GET /content/tutorials-prerelease/_nav (gated live feed) --- + + /** + * preReleaseNavHandler — live gated nav feed for ROLE_GATED tutorials. + * + * Mounted at GET /content/tutorials-prerelease/_nav (server.js, near line 850). + * Requires the Tutorial.PreRelease scope (XSUAA-enforced by the approuter route + * that maps ^/tutorials-prerelease/(.*)$ to /content/tutorials-prerelease/$1). + * + * Returns { version, count, tutorials } where each tutorial is the same shape + * as navHandlerFallback items. Cache-Control is ALWAYS private, no-store (gated + * content — must NOT be cached by shared/CDN caches). + * + * Does NOT read or write the shared slug-keyed in-process `cache` (the #3099 + * cache-leak rule — ROLE_GATED bytes must never enter the shared cache). + */ + async function preReleaseNavHandler(req, res) { + const { ContentFiles, ContentCurrent } = cds.entities(namespace); + + try { + const activeVersion = await getActiveVersion(); + + // Enumerate ContentCurrent slugs (Option B read path) or fall back to + // ContentFiles — same logic as navHandlerFallback; reuses the same read. + const contentRows = (isDeltaRead() && ContentCurrent) + ? await SELECT.from(ContentCurrent).columns('slug', 'sizeBytes') + : (activeVersion !== null + ? await SELECT.from(ContentFiles).where({ version: activeVersion }).columns('slug', 'sizeBytes') + : []); + + const slugs = contentRows.filter(r => + r.slug !== '__nav__' && r.slug !== '__404__' && r.slug !== '__shell__' + ).map(r => r.slug); + + if (slugs.length === 0) { + res.setHeader('Cache-Control', 'private, no-store'); + return res.json({ version: activeVersion, count: 0, tutorials: [] }); + } + + const slugSet = new Set(slugs); + // Gated feed: visibilityFilter 'ROLE_GATED' — returns ONLY ROLE_GATED tutorials. + // Does NOT use the shared slug-keyed `cache` (cache-leak rule #3099). + const tutorials = await buildNavTutorials(slugSet, contentRows, { visibilityFilter: 'ROLE_GATED' }); + + res.setHeader('Cache-Control', 'private, no-store'); + return res.json({ version: activeVersion, count: tutorials.length, tutorials }); + } catch (err) { + console.error('[content/prerelease-nav]', err instanceof Error ? err.message : String(err)); + res.status(500).json({ error: 'Pre-release navigation catalog failed' }); + } + } + async function navHandler(req, res) { const { ContentFiles } = cds.entities(namespace); @@ -2378,6 +2468,7 @@ export function createContentHandlers({ namespace = 'com.sap.developers.ims', ap excludedSlugsHandler, getTutorialSource, navHandler, + preReleaseNavHandler, rollbackHandler, orphanPurgeHandler, beginHandler, @@ -2415,6 +2506,7 @@ export const commitHandler = _defaults.commitHandler; export const abortHandler = _defaults.abortHandler; export const pipelineLogFailureHandler = _defaults.pipelineLogFailureHandler; export const quarantineIngestHandler = _defaults.quarantineIngestHandler; +export const preReleaseNavHandler = _defaults.preReleaseNavHandler; export const pageServeHandler = _defaults.pageServeHandler; export const authorServeHandler = _defaults.authorServeHandler; export const advocateServeHandler = _defaults.advocateServeHandler; diff --git a/srv/__tests__/lib/prerelease-nav.test.js b/srv/__tests__/lib/prerelease-nav.test.js new file mode 100644 index 000000000..fb932b764 --- /dev/null +++ b/srv/__tests__/lib/prerelease-nav.test.js @@ -0,0 +1,170 @@ +// srv/__tests__/lib/prerelease-nav.test.js +// +// TDD for Task 2: Live gated nav feed for ROLE_GATED tutorials (#3168). +// Tests that preReleaseNavHandler returns ONLY ROLE_GATED tutorials (incl. +// standalone ones not in any published mission), with Cache-Control: private, +// no-store, and the correct item shape. +// +// Also asserts the inverse: the public navHandler fallback excludes ROLE_GATED. + +import cds from '@sap/cds'; +import { describe, it, expect, beforeAll, beforeEach } from 'vitest'; +import { gzipSync } from 'node:zlib'; +import { preReleaseNavHandler, navHandler } from '../../lib/content-store.js'; + +const NS = 'com.sap.developers.ims'; + +// --- Mock Express req/res helpers --- + +function mockReq() { + return { + url: '/content/tutorials-prerelease/_nav', + params: {}, + headers: {}, + get(k) { return this.headers[k.toLowerCase()]; }, + }; +} + +function mockRes() { + const r = { + headers: {}, + body: null, + _status: 200, + status(code) { r._status = code; return r; }, + setHeader(k, v) { r.headers[k] = v; }, + getHeader(k) { return r.headers[k]; }, + json(b) { r.body = b; return r; }, + send(b) { r.body = b; return r; }, + end(b) { if (b != null) r.body = b; return r; }, + }; + return r; +} + +cds.test('serve', '--project', '.', '--in-memory'); + +// --- Seed helpers --- + +async function seedManifestIfNeeded() { + const { ContentManifest } = cds.entities(NS); + const existing = await SELECT.one.from(ContentManifest).where({ status: 'ACTIVE' }); + if (!existing) { + await INSERT.into(ContentManifest).entries({ + version: 1, status: 'ACTIVE', activatedAt: new Date().toISOString(), + }); + } +} + +/** + * Seed a tutorial with ContentFiles (version 1) + Tutorials row. + * Uses ContentFiles (not ContentCurrent) because isDeltaRead()=false in the test + * environment — navHandlerFallback and preReleaseNavHandler fall through to + * ContentFiles when the flag is off. + * @param {string} slug + * @param {{ visibility: string, status?: string }} opts + */ +async function seedTutorial(slug, { visibility = 'LISTED', status = 'ACTIVE' } = {}) { + const { ContentFiles, Tutorials } = cds.entities(NS); + const html = `Content for ${slug}`; + + await seedManifestIfNeeded(); + + await INSERT.into(ContentFiles).entries({ + slug, version: 1, + content: gzipSync(Buffer.from(html)), + sourceContent: gzipSync(Buffer.from(`---\ntitle: ${slug}\n---\n`)), + contentHash: `hash-${slug}`, sourceHash: `src-${slug}`, + mimeType: 'text/html', sizeBytes: html.length, + }); + + await INSERT.into(Tutorials).entries({ + ID: cds.utils.uuid(), + slug, title: `Title ${slug}`, + status, visibility, + experienceTag: 'Beginner', + averageTimeToComplete: 10, + }); +} + +describe('preRelease nav feed', () => { + beforeAll(async () => { + await cds.connect.to('db'); + }); + + beforeEach(async () => { + const { ContentManifest, ContentFiles, Tutorials } = cds.entities(NS); + await DELETE.from(ContentFiles); + await DELETE.from(ContentManifest); + await DELETE.from(Tutorials); + }); + + it('gated nav feed returns only ROLE_GATED incl. standalone, no-store', async () => { + // Seed three tutorials: one LISTED, two ROLE_GATED. + // `gated-standalone` is explicitly NOT in any published mission — + // the feed must return it (this is the key regression guard). + await seedTutorial('listed-a', { visibility: 'LISTED' }); + await seedTutorial('gated-standalone', { visibility: 'ROLE_GATED' }); + await seedTutorial('gated-b', { visibility: 'ROLE_GATED' }); + + const res = mockRes(); + await preReleaseNavHandler(mockReq(), res); + + expect(res._status).toBe(200); + const slugs = res.body.tutorials.map(t => t.slug); + + // Both ROLE_GATED tutorials must appear (incl. standalone). + expect(slugs).toEqual(expect.arrayContaining(['gated-standalone', 'gated-b'])); + // The LISTED tutorial must NOT appear. + expect(slugs).not.toContain('listed-a'); + + // Cache-Control must be private, no-store (not cacheable publicly). + expect(res.headers['Cache-Control']).toBe('private, no-store'); + + // Response shape check. + expect(res.body).toHaveProperty('version'); + expect(res.body).toHaveProperty('count'); + expect(typeof res.body.count).toBe('number'); + + // Item shape: each entry must have the required fields. + for (const t of res.body.tutorials) { + expect(t).toHaveProperty('slug'); + expect(t).toHaveProperty('title'); + expect(t).toHaveProperty('time'); + expect(t).toHaveProperty('level'); + expect(t).toHaveProperty('stepCount'); + expect(t).toHaveProperty('displayTags'); + } + }); + + it('public navHandler fallback excludes ROLE_GATED tutorials', async () => { + // Seed the same set so we can confirm the public fallback excludes ROLE_GATED. + // The public navHandler serves the baked __nav__ blob when present; with no + // blob seeded it falls back to navHandlerFallback which must also exclude. + await seedTutorial('listed-a', { visibility: 'LISTED' }); + await seedTutorial('gated-standalone', { visibility: 'ROLE_GATED' }); + await seedTutorial('gated-b', { visibility: 'ROLE_GATED' }); + + const res = mockRes(); + await navHandler(mockReq(), res); + + expect(res._status).toBe(200); + const slugs = res.body.tutorials.map(t => t.slug); + + // LISTED must appear. + expect(slugs).toContain('listed-a'); + // ROLE_GATED must NOT appear in the public feed. + expect(slugs).not.toContain('gated-standalone'); + expect(slugs).not.toContain('gated-b'); + }); + + it('INACTIVE ROLE_GATED tutorials are excluded from gated feed', async () => { + await seedTutorial('gated-active', { visibility: 'ROLE_GATED', status: 'ACTIVE' }); + await seedTutorial('gated-inactive', { visibility: 'ROLE_GATED', status: 'INACTIVE' }); + + const res = mockRes(); + await preReleaseNavHandler(mockReq(), res); + + const slugs = res.body.tutorials.map(t => t.slug); + expect(slugs).toContain('gated-active'); + expect(slugs).not.toContain('gated-inactive'); + }); +}); diff --git a/srv/lib/content-store.js b/srv/lib/content-store.js index 14eaa1afd..580ec133b 100644 --- a/srv/lib/content-store.js +++ b/srv/lib/content-store.js @@ -22,6 +22,7 @@ export const sourceHashesHandler = mod.sourceHashesHandler; export const excludedSlugsHandler = mod.excludedSlugsHandler; export const getTutorialSource = mod.getTutorialSource; export const navHandler = mod.navHandler; +export const preReleaseNavHandler = mod.preReleaseNavHandler; export const rollbackHandler = mod.rollbackHandler; export const orphanPurgeHandler = mod.orphanPurgeHandler; export const beginHandler = mod.beginHandler; diff --git a/srv/server.js b/srv/server.js index 8134079e7..ffd50cfc6 100644 --- a/srv/server.js +++ b/srv/server.js @@ -32,7 +32,7 @@ import { decideHandler } from './lib/branch/decide.js'; import { getTagLabelMap } from './lib/tag-label-map.js'; import { myProgressHandler } from './lib/my-progress-handler.js'; import { basicAuthMiddleware } from './lib/tech-user-auth.js'; -import { contentAuthMiddleware, publishHandler, serveHandler, markdownServeHandler, pageServeHandler, authorServeHandler, advocateServeHandler, hashesHandler, sourceHashesHandler, excludedSlugsHandler, navHandler, rollbackHandler, orphanPurgeHandler, invalidateRenderCache, beginHandler, appendHandler, commitHandler, abortHandler, pipelineLogFailureHandler, quarantineIngestHandler, snippetDepsHandler } from './lib/content-store.js'; +import { contentAuthMiddleware, publishHandler, serveHandler, markdownServeHandler, pageServeHandler, authorServeHandler, advocateServeHandler, hashesHandler, sourceHashesHandler, excludedSlugsHandler, navHandler, preReleaseNavHandler, rollbackHandler, orphanPurgeHandler, invalidateRenderCache, beginHandler, appendHandler, commitHandler, abortHandler, pipelineLogFailureHandler, quarantineIngestHandler, snippetDepsHandler } from './lib/content-store.js'; import { imageSourceHandler } from './lib/image-source-handler.js'; import { imageIngestHandler } from './lib/image-ingest-handler.js'; import { attachmentSourceHandler } from './lib/attachment-source-handler.js'; @@ -854,6 +854,11 @@ cds.on('bootstrap', (app) => { // bypass the public 404 gate and are served — but are never cached publicly. // The `gated` flag is passed via closure from this server-side mount, NOT via // any client-settable header, so it cannot be spoofed. + // + // _nav route: live gated nav feed — lists ONLY ROLE_GATED tutorials (#3168). + // Registered BEFORE the *slug wildcard so `_nav` is not swallowed as a slug. + // Cache-Control: private, no-store (never cached by shared/CDN caches). + app.get('/content/tutorials-prerelease/_nav', (req, res) => preReleaseNavHandler(req, res)); app.get('/content/tutorials-prerelease/*slug', (req, res) => serveHandler(req, res, { gated: true })); // Legacy AEM `.model.json` compatibility for SAP Discovery Center (#DC cards). // Approuter maps ^/tutorials/.model.json$ → here. See srv/lib/model-json.js. From e680a545a79371c0e2a843d9c8850e2406550188 Mon Sep 17 00:00:00 2001 From: Thomas Jung Date: Sat, 21 Nov 2026 19:11:18 -0500 Subject: [PATCH 03/11] feat(prerelease): QA-style prerelease build channel (#3168) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extend Channel union to 'prod' | 'qa' | 'prerelease' in fetch-tutorials.ts - parseChannel accepts --channel prerelease (throws Unknown channel on unknown) - getQaCacheDir → .tutorial-cache-prerelease - getHugoContentDir → hugo/content-prerelease - getNavJsonDir → hugo/static-prerelease/tutorials - browseDataFile → hugo/data-prerelease/browse.json - buildAllCards uses /tutorials-prerelease prefix for prerelease - main(): writes content-prerelease/_index.md + tutorial-navigator/_index.md - main(): filters allTutorials to visibility===ROLE_GATED for prerelease channel - main(): skips discovery baseline upload (non-prod, same as qa) - main(): allows feed drift on fast-path reuse (same as qa) - main(): dimensionsPath → hugo/data-prerelease/image_dimensions.json - New hugo.prerelease.toml: dataDir=data-prerelease, params.prerelease=true, baseURL=/tutorials-prerelease/ - New scripts/sync-island-manifest-prerelease.cjs: copies island_manifest.json to data-prerelease/ - package.json: fetch-tutorials:prerelease, build:prerelease, publish-content:prerelease, prerelease:full build:prerelease reuses verify-qa-build.ts (takes dir as argv[2]) for public-prerelease - TDD: scripts/__tests__/fetch-tutorials-channel.test.ts, 16 tests pass (green after impl) - Full channel build deferred to deploy-time (CAP_BASE_URL not set locally) - Note: build:prerelease not in build:all, same as QA pattern; deploy wiring is Task 6 --- hugo.prerelease.toml | 66 ++++++++++ package.json | 4 + .../__tests__/fetch-tutorials-channel.test.ts | 65 +++++++++ scripts/fetch-tutorials.ts | 124 ++++++++++++++---- scripts/sync-island-manifest-prerelease.cjs | 43 ++++++ 5 files changed, 279 insertions(+), 23 deletions(-) create mode 100644 hugo.prerelease.toml create mode 100644 scripts/__tests__/fetch-tutorials-channel.test.ts create mode 100644 scripts/sync-island-manifest-prerelease.cjs diff --git a/hugo.prerelease.toml b/hugo.prerelease.toml new file mode 100644 index 000000000..270f497f0 --- /dev/null +++ b/hugo.prerelease.toml @@ -0,0 +1,66 @@ +# hugo.prerelease.toml — sibling of hugo/hugo.toml, used by `npm run build:prerelease` +# Prerelease Hugo config: reads from hugo/content-prerelease/, writes to hugo/public-prerelease/. +# Stripped of prod-only output formats (RSS, sitemap, robots, llms*) — prerelease is internal-only. +# Shows ROLE_GATED tutorials only — the navigator IS the root, same as QA. +# Invocation: cd hugo && hugo --config ../hugo.prerelease.toml --minify + +baseURL = "/tutorials-prerelease/" +languageCode = "en-us" +title = "[Prerelease] SAP Tutorials Preview" +contentDir = "content-prerelease" +dataDir = "data-prerelease" +staticDir = "static-prerelease" +publishDir = "public-prerelease" + +# Prerelease is internal-only — suppress sitemap. Taxonomy/term pages stay enabled +# because the home template references .Site.Taxonomies; we override their +# outputs below to drop RSS feeds. +disableKinds = ["sitemap"] + +# Defense-in-depth: even if future tasks ever generate non-tutorial pages under +# content-prerelease/, never render mission/group/me/search shells on prerelease. +ignoreFiles = ["^(missions|groups|me|search)/.*$"] + +[params] + prerelease = true + prereleaseBannerText = "Prerelease preview — ROLE_GATED tutorials not yet publicly listed." + +[build] + writeStats = true + +[markup] + [markup.goldmark] + [markup.goldmark.renderer] + unsafe = true + [markup.goldmark.parser] + [markup.goldmark.parser.attribute] + block = true + title = true + [markup.goldmark.extensions] + [markup.goldmark.extensions.passthrough] + enable = true + [markup.goldmark.extensions.passthrough.delimiters] + block = [['$$', '$$']] + inline = [['$', '$']] + [markup.highlight] + noClasses = false + codeFences = true + guessSyntax = false + lineNos = false + tabWidth = 2 + +# U1 Object Page floorplan as the default tutorial layout — mirrors prod cascade +# so prerelease pages render with the same visual fidelity. Path matches the content +# location (content-prerelease/tutorials/**), which Hugo resolves before applying baseURL. +[[cascade]] + layout = "u1-object-page" + [cascade._target] + path = "/tutorials/**" + kind = "page" + +[outputs] + home = ["HTML"] + section = ["HTML"] + page = ["HTML"] + taxonomy = ["HTML"] + term = ["HTML"] diff --git a/package.json b/package.json index e76ac6f5c..932650946 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,10 @@ "build:qa": "node scripts/sync-island-manifest-qa.cjs && hugo --source hugo --config ../hugo.qa.toml --minify && tsx scripts/verify-qa-build.ts hugo/public-qa", "publish-content:qa": "tsx scripts/publish-content.ts --channel qa", "qa:full": "npm run fetch-tutorials:qa && npm run build:qa && npm run publish-content:qa", + "fetch-tutorials:prerelease": "tsx scripts/fetch-tutorials.ts --target hugo --channel prerelease", + "build:prerelease": "node scripts/sync-island-manifest-prerelease.cjs && hugo --source hugo --config ../hugo.prerelease.toml --minify && tsx scripts/verify-qa-build.ts hugo/public-prerelease", + "publish-content:prerelease": "tsx scripts/publish-content.ts --channel prerelease", + "prerelease:full": "npm run fetch-tutorials:prerelease && npm run build:prerelease && npm run publish-content:prerelease", "setup-dev-data": "cds bind --exec -- node scripts/setup-dev-data.cjs", "seed-poc-puzzle": "cds bind --exec -- node srv/lib/seed-poc-puzzle.js", "export:advocates": "cds bind --exec -- node scripts/export-advocates.cjs", diff --git a/scripts/__tests__/fetch-tutorials-channel.test.ts b/scripts/__tests__/fetch-tutorials-channel.test.ts new file mode 100644 index 000000000..f9a1eb29d --- /dev/null +++ b/scripts/__tests__/fetch-tutorials-channel.test.ts @@ -0,0 +1,65 @@ +import { describe, it, expect } from 'vitest' +import { + parseChannel, + getQaCacheDir, + getHugoContentDir, + getNavJsonDir, + browseDataFile, +} from '../fetch-tutorials' + +describe('prerelease channel — parseChannel', () => { + it('parses --channel prerelease', () => { + expect(parseChannel(['node', 'x', '--channel', 'prerelease'])).toBe('prerelease') + }) + it('still parses --channel qa', () => { + expect(parseChannel(['node', 'x', '--channel', 'qa'])).toBe('qa') + }) + it('still defaults to prod with no --channel flag', () => { + expect(parseChannel(['node', 'x'])).toBe('prod') + }) + it('still rejects an unknown channel', () => { + expect(() => parseChannel(['node', 'x', '--channel', 'staging'])).toThrow('Unknown channel') + }) +}) + +describe('prerelease channel — dir helpers', () => { + it('getQaCacheDir maps prerelease to .tutorial-cache-prerelease', () => { + expect(getQaCacheDir('prerelease').replace(/\\/g, '/')).toMatch(/\.tutorial-cache-prerelease$/) + }) + it('getQaCacheDir still maps qa to .tutorial-cache-qa', () => { + expect(getQaCacheDir('qa').replace(/\\/g, '/')).toMatch(/\.tutorial-cache-qa$/) + }) + it('getQaCacheDir still maps prod to .tutorial-cache', () => { + expect(getQaCacheDir('prod').replace(/\\/g, '/')).toMatch(/\.tutorial-cache$/) + }) + + it('getHugoContentDir maps prerelease to hugo/content-prerelease', () => { + expect(getHugoContentDir('prerelease').replace(/\\/g, '/')).toMatch(/hugo\/content-prerelease$/) + }) + it('getHugoContentDir still maps qa to hugo/content-qa', () => { + expect(getHugoContentDir('qa').replace(/\\/g, '/')).toMatch(/hugo\/content-qa$/) + }) + it('getHugoContentDir still maps prod to hugo/content', () => { + expect(getHugoContentDir('prod').replace(/\\/g, '/')).toMatch(/hugo\/content$/) + }) + + it('getNavJsonDir maps prerelease to hugo/static-prerelease/tutorials', () => { + expect(getNavJsonDir('hugo', 'prerelease').replace(/\\/g, '/')).toMatch(/hugo\/static-prerelease\/tutorials$/) + }) + it('getNavJsonDir still maps qa to hugo/static-qa/tutorials', () => { + expect(getNavJsonDir('hugo', 'qa').replace(/\\/g, '/')).toMatch(/hugo\/static-qa\/tutorials$/) + }) + it('getNavJsonDir still maps prod to hugo/static/tutorials', () => { + expect(getNavJsonDir('hugo', 'prod').replace(/\\/g, '/')).toMatch(/hugo\/static\/tutorials$/) + }) + + it('browseDataFile maps prerelease to hugo/data-prerelease/browse.json', () => { + expect(browseDataFile('prerelease').replace(/\\/g, '/')).toMatch(/hugo\/data-prerelease\/browse\.json$/) + }) + it('browseDataFile still maps qa to hugo/data-qa/browse.json', () => { + expect(browseDataFile('qa').replace(/\\/g, '/')).toMatch(/hugo\/data-qa\/browse\.json$/) + }) + it('browseDataFile still maps prod to hugo/data/browse.json', () => { + expect(browseDataFile('prod').replace(/\\/g, '/')).toMatch(/hugo\/data\/browse\.json$/) + }) +}) diff --git a/scripts/fetch-tutorials.ts b/scripts/fetch-tutorials.ts index a61e7b749..56b2d4dc2 100644 --- a/scripts/fetch-tutorials.ts +++ b/scripts/fetch-tutorials.ts @@ -76,26 +76,26 @@ const CONCURRENCY = 5 // tutorials in one fetch run; logged at the end as a one-line summary. const globalCallStats: ExpandStats = { calls: 0, hits: 0, errors: 0 } -export type Channel = 'prod' | 'qa' +export type Channel = 'prod' | 'qa' | 'prerelease' export function parseChannel(argv: string[] = process.argv): Channel { const idx = argv.indexOf('--channel') if (idx === -1) return 'prod' const v = argv[idx + 1] - if (v !== 'prod' && v !== 'qa') throw new Error(`Unknown channel: ${v}`) + if (v !== 'prod' && v !== 'qa' && v !== 'prerelease') throw new Error(`Unknown channel: ${v}`) return v } export function getQaCacheDir(channel: Channel): string { - return channel === 'qa' - ? join(__dirname, '..', '.tutorial-cache-qa') - : join(__dirname, '..', '.tutorial-cache') + if (channel === 'qa') return join(__dirname, '..', '.tutorial-cache-qa') + if (channel === 'prerelease') return join(__dirname, '..', '.tutorial-cache-prerelease') + return join(__dirname, '..', '.tutorial-cache') } export function getHugoContentDir(channel: Channel): string { - return channel === 'qa' - ? join(__dirname, '..', 'hugo', 'content-qa') - : join(__dirname, '..', 'hugo', 'content') + if (channel === 'qa') return join(__dirname, '..', 'hugo', 'content-qa') + if (channel === 'prerelease') return join(__dirname, '..', 'hugo', 'content-prerelease') + return join(__dirname, '..', 'hugo', 'content') } /** @@ -186,6 +186,39 @@ export function qaNavigatorPageMarkdown(): string { return qaHomeIndexMarkdown() } +/** + * Front matter for the prerelease site's root `_index.md`. + * + * Mirrors `qaHomeIndexMarkdown` exactly, but uses `params.prerelease` (set by + * `hugo.prerelease.toml`) instead of `params.qa` to gate nav affordances + * (data-search-base="/prerelease-search", etc.) in the layouts. + * The prerelease channel shows ROLE_GATED tutorials only — the navigator IS + * the root, same as QA. + */ +export function prereleaseHomeIndexMarkdown(): string { + return [ + '---', + 'title: "[Prerelease] Tutorial navigator"', + 'description: "Prerelease preview — browse ROLE_GATED tutorials not yet publicly listed."', + 'type: "tutorial-navigator"', + 'layout: "list"', + '---', + '', + ].join('\n') +} + +/** + * Front matter for the prerelease site's dedicated `/tutorial-navigator/` section + * (`content-prerelease/tutorial-navigator/_index.md`). + * + * Mirrors the QA pattern (#1675): emitted at `public-prerelease/tutorial-navigator/index.html`, + * published as `page-tutorial-navigator` BLOB to `tutorials-hana-prerelease`. + * Byte-identical to `prereleaseHomeIndexMarkdown` (same navigator layout + prerelease markers). + */ +export function prereleaseNavigatorPageMarkdown(): string { + return prereleaseHomeIndexMarkdown() +} + /** * Prune stale `.md` files from `cacheDir` — any whose slug is NOT in @@ -246,7 +279,10 @@ export function getOutputDir(target: BuildTarget, channel: Channel = 'prod'): st export function getNavJsonDir(target: BuildTarget, channel: Channel = 'prod'): string { if (target === 'hugo') { - const staticDir = channel === 'qa' ? 'static-qa' : 'static' + const staticDir = + channel === 'qa' ? 'static-qa' : + channel === 'prerelease' ? 'static-prerelease' : + 'static' return join(__dirname, '..', 'hugo', staticDir, 'tutorials') } return join(__dirname, '..', 'site', 'tutorials') @@ -887,6 +923,21 @@ async function main() { console.log(' [channel] wrote content-qa/tutorial-navigator/_index.md (page-tutorial-navigator)\n') } + // Prerelease channel: same no-homepage pattern as QA — the navigator IS the + // root. Mirrors QA's _index.md + tutorial-navigator/ section pattern so the + // same navigator layout resolves, using site.Params.prerelease for gating. + if (target === 'hugo' && channel === 'prerelease') { + const prereleaseRoot = getHugoContentDir(channel) + mkdirSync(prereleaseRoot, { recursive: true }) + writeFileSync(join(prereleaseRoot, '_index.md'), prereleaseHomeIndexMarkdown(), 'utf-8') + console.log(' [channel] wrote content-prerelease/_index.md (navigator layout as prerelease root)\n') + + const prereleaseNavDir = join(prereleaseRoot, 'tutorial-navigator') + mkdirSync(prereleaseNavDir, { recursive: true }) + writeFileSync(join(prereleaseNavDir, '_index.md'), prereleaseNavigatorPageMarkdown(), 'utf-8') + console.log(' [channel] wrote content-prerelease/tutorial-navigator/_index.md (page-tutorial-navigator)\n') + } + let allTutorials: DiscoveredTutorial[] // Tier of the discovery result. Only 'github' is authoritative enough to drive // the fail-loud slug-existence catalog below — a disk/hana/rest fallback may be @@ -1150,12 +1201,13 @@ async function main() { currentFingerprint: decisionFingerprint, currentPipelineToken, sidecarPipelineToken: restoredSidecar?.pipelineToken, - // QA is an author-preview channel that rebuilds rarely, so its cached feed - // fingerprint is almost always stale vs prod's frequently-republished - // catalog — which would force a ~10-min full regen for a single-slug - // preview. Allow reuse of cached non-target pages despite feed drift on QA - // (the target slug is always regenerated). Prod keeps strict freshness. - allowFeedDrift: channel === 'qa', + // QA and prerelease are author-preview channels that rebuild rarely, so + // their cached feed fingerprints are almost always stale vs prod's + // frequently-republished catalog — which would force a ~10-min full regen + // for a single-slug preview. Allow reuse of cached non-target pages despite + // feed drift on QA/prerelease (the target slug is always regenerated). + // Prod keeps strict freshness. + allowFeedDrift: channel === 'qa' || channel === 'prerelease', }) const reuseNavBySlug = restoredSidecar ? navEntriesBySlug(restoredSidecar) : new Map>() const reuseAuthorRowsBySlug = new Map() @@ -1309,6 +1361,20 @@ async function main() { if (m.visibility) visibilityBySlug.set(m.slug.toLowerCase(), m.visibility) } + // [#3168] Prerelease channel: keep only ROLE_GATED tutorials. The visibility + // map is built from the cached /build/catalog payload (loadCapCache above). + // Fail-open: if the map is empty (no catalog cached yet) we let all tutorials + // through so the build doesn't hard-fail on a cold cache; the resulting + // empty-ish prerelease channel is correct behavior when no ROLE_GATED + // tutorials exist in the catalog. + if (channel === 'prerelease') { + const before = allTutorials.length + allTutorials = allTutorials.filter(t => + visibilityBySlug.get(t.slug.toLowerCase()) === 'ROLE_GATED' + ) + console.log(`[channel=prerelease] filtered to ROLE_GATED tutorials: ${allTutorials.length} of ${before}`) + } + const unexpandedDirectiveHits: Array<{ slug: string; tokens: string[] }> = [] // A compose-time DirectiveParseError (e.g. ::include of a snippet that didn't @@ -2091,7 +2157,10 @@ async function main() { try { const roster = await fetchAdvocateRoster() const advocates = advocateLoginToSlug(roster) - const dataDir = join(__dirname, '..', 'hugo', channel === 'qa' ? 'data-qa' : 'data') + const dataDir = join(__dirname, '..', 'hugo', + channel === 'qa' ? 'data-qa' : + channel === 'prerelease' ? 'data-prerelease' : + 'data') // Active/published catalog slugs (lowercase) — same ACTIVE-only set the // navigator/browse use (status='ACTIVE' or null, srv/lib/build-catalog.js). // Excludes INACTIVE/soft-deleted tutorials + stale-cache slugs from the @@ -2103,7 +2172,7 @@ async function main() { // cannot rebuild authorRows — can re-hydrate it from the deployed // approuter and avoid wiping /authors/* (scripts/seed-authors-from-deployed.ts). const publishFile = - channel === 'qa' + channel === 'qa' || channel === 'prerelease' ? undefined : join(__dirname, '..', 'hugo', 'static', 'author_index.json') // Issue #2354: conference sessions per author (fail-open — empty map on @@ -2327,9 +2396,14 @@ async function main() { // ────────────────────────────────────────────────────────────────────────── // Channel-aware browse.json target. Prod → hugo/data/browse.json (Hugo default -// dataDir); QA → hugo/data-qa/browse.json (hugo.qa.toml sets dataDir="data-qa"). +// dataDir); QA → hugo/data-qa/browse.json (hugo.qa.toml sets dataDir="data-qa"); +// prerelease → hugo/data-prerelease/browse.json (hugo.prerelease.toml sets dataDir="data-prerelease"). export function browseDataFile(channel: Channel): string { - const dir = join(__dirname, '..', 'hugo', channel === 'qa' ? 'data-qa' : 'data') + const dataSubDir = + channel === 'qa' ? 'data-qa' : + channel === 'prerelease' ? 'data-prerelease' : + 'data' + const dir = join(__dirname, '..', 'hugo', dataSubDir) return join(dir, 'browse.json') } @@ -2664,7 +2738,10 @@ function writeBrowseData( const tutorialMetaMap = new Map( tutorialMetas.map(m => [m.slug, m]), ) - const all: BrowseCardItem[] = buildAllCards(tuts, missions, hierarchies, standaloneGroups, tutorialMetaMap, channel === 'qa' ? '/tutorials-qa' : '/tutorials') + const all: BrowseCardItem[] = buildAllCards(tuts, missions, hierarchies, standaloneGroups, tutorialMetaMap, + channel === 'qa' ? '/tutorials-qa' : + channel === 'prerelease' ? '/tutorials-prerelease' : + '/tutorials') // Featured: prefer admin-curated FeaturedTasks (top 10 missions ordered by // featuredOrder); fall back to the regex-sieved catalog-order picker @@ -2700,9 +2777,10 @@ const isMainModule = process.argv[1] && ( ) if (isMainModule) { const channelForExport = parseChannel(process.argv) - const dimensionsPath = channelForExport === 'qa' - ? join(__dirname, '..', 'hugo', 'data-qa', 'image_dimensions.json') - : join(__dirname, '..', 'hugo', 'data', 'image_dimensions.json') + const dimensionsPath = + channelForExport === 'qa' ? join(__dirname, '..', 'hugo', 'data-qa', 'image_dimensions.json') : + channelForExport === 'prerelease' ? join(__dirname, '..', 'hugo', 'data-prerelease', 'image_dimensions.json') : + join(__dirname, '..', 'hugo', 'data', 'image_dimensions.json') main() .then(() => { flushDimensionsCache() diff --git a/scripts/sync-island-manifest-prerelease.cjs b/scripts/sync-island-manifest-prerelease.cjs new file mode 100644 index 000000000..ecce302cc --- /dev/null +++ b/scripts/sync-island-manifest-prerelease.cjs @@ -0,0 +1,43 @@ +// scripts/sync-island-manifest-prerelease.cjs +// +// Bridges the Vite island fingerprint manifest into the prerelease Hugo build. +// Mirrors scripts/sync-island-manifest-qa.cjs exactly, retargeted to the +// prerelease data/public dirs (hugo/data-prerelease/). +// +// The prerelease build (hugo.prerelease.toml) sets `dataDir = "data-prerelease"`, +// which *replaces* Hugo's data root rather than merging with `data/`. So during +// `build:prerelease`, hugo/data/island_manifest.json is invisible: +// `site.Data.island_manifest` is undefined and island-src.html falls back to +// the UNHASHED "/js/.js" path. Vite emits only content-hashed files for +// the fingerprinted islands (validation, navigator, ...), so the unhashed URL +// 404s on the approuter and the island never mounts. +// +// Fix: copy hugo/data/island_manifest.json into hugo/data-prerelease/ right +// before the prerelease Hugo build, so prerelease bakes the same hashed paths +// as prod (both served from the shared approuter static/js/ tree). +// +// Soft by design: if the source manifest is absent (e.g. a bare +// `build:prerelease` without a prior `build:island-manifest`), this warns and +// continues rather than hard-failing — the real gate is scripts/verify-qa-build.ts +// (reused for prerelease), which fails the build if any page baked an unhashed +// island fallback. + +const { copyFileSync, existsSync, mkdirSync } = require('node:fs'); +const { join, resolve, dirname } = require('node:path'); + +const REPO_ROOT = resolve(__dirname, '..'); +const SRC = join(REPO_ROOT, 'hugo', 'data', 'island_manifest.json'); +const DEST = join(REPO_ROOT, 'hugo', 'data-prerelease', 'island_manifest.json'); + +if (!existsSync(SRC)) { + console.warn( + `[sync-island-manifest-prerelease] source manifest not found at ${SRC}. ` + + 'Run `npm run build:island-manifest` (after building the islands) first. ' + + 'Prerelease HTML will bake unhashed island paths until then — verify-qa-build.ts will fail the build.', + ); + process.exit(0); +} + +mkdirSync(dirname(DEST), { recursive: true }); +copyFileSync(SRC, DEST); +console.log('[sync-island-manifest-prerelease] copied island_manifest.json -> hugo/data-prerelease/'); From 1d1826c8020ea691fcbcb3513925e0a5c975d71b Mon Sep 17 00:00:00 2001 From: Thomas Jung Date: Sat, 21 Nov 2026 19:19:39 -0500 Subject: [PATCH 04/11] feat(prerelease): navigator template prerelease channel branch (#3168) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extend both `{{ if not site.Params.qa }}` gates to also suppress the browse-pill and homepage discovery sections (hero, featured, recent, topics) when `site.Params.prerelease` is set. - Add `{{ else if site.Params.prerelease }}` branch on the island mount node: emits `data-nav-base="/tutorials-prerelease"`, `data-href-base="/tutorials-prerelease"`, `data-client-search="true"`. No `data-search-base` (prerelease uses client-side search only — `clientSearch=true` in TutorialNavigator.vue disables server search). - Add a "Pre-release" fd-object-status badge above the island mount so holders know they are on the gated surface. - Add `$hrefBase = "/tutorials-prerelease"` assignment in the SSR featured-rail block (defensive; that section is already gated off for prerelease, but keeps the value consistent). --- hugo/layouts/tutorial-navigator/list.html | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/hugo/layouts/tutorial-navigator/list.html b/hugo/layouts/tutorial-navigator/list.html index e5d6b896d..168ede07c 100644 --- a/hugo/layouts/tutorial-navigator/list.html +++ b/hugo/layouts/tutorial-navigator/list.html @@ -27,7 +27,7 @@ {{- end -}}
- {{ if not site.Params.qa }} + {{ if and (not site.Params.qa) (not site.Params.prerelease) }}
@@ -38,7 +38,13 @@