From 796bc06524703f257b9afa44578d259f9a68776c Mon Sep 17 00:00:00 2001 From: Russ Rutledge Date: Tue, 27 Oct 2026 13:40:37 -0500 Subject: [PATCH 1/3] Keep Code-node JavaScript in src/*.js and build it into the workflow JSON Each Code node's JavaScript now lives in its own file under src/, so a pull request shows a code change as ordinary lines of JavaScript. make build writes the code back into the workflow JSON, make extract seeds src/ from the JSON, and a CI check fails a pull request whose JSON and src/ disagree. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AEavKGR3wFFUQXR9W16mSQ --- .github/workflows/check-code-nodes.yml | 22 ++ Makefile | 15 ++ USAGE.md | 18 ++ scripts/code-nodes.js | 197 ++++++++++++++++++ .../isc-gdrive/build-actual-structure.js | 46 ++++ .../isc-gdrive/check-missing-folders.js | 24 +++ .../collect-existing-folder-descriptions.js | 38 ++++ .../isc-gdrive/flatten-folders-to-create.js | 149 +++++++++++++ .../isc-gdrive/set-missing-folders.js | 119 +++++++++++ .../slack-welcome-message-block-kit.js | 63 ++++++ src/send-bulk-dm/collect-members.js | 7 + src/send-bulk-dm/init-pagination.js | 3 + src/send-bulk-dm/output-all-members.js | 3 + .../collect-members.js | 7 + .../init-pagination.js | 3 + .../output-all-members.js | 3 + .../isc-crier/build-slack-blocks.js | 20 ++ src/zoom-recaps-to-slack/apply-filter.js | 20 ++ src/zoom-recaps-to-slack/apply-full-notes.js | 97 +++++++++ src/zoom-recaps-to-slack/attach-fields.js | 5 + src/zoom-recaps-to-slack/build-candidates.js | 101 +++++++++ src/zoom-recaps-to-slack/format-full-notes.js | 12 ++ src/zoom-recaps-to-slack/format-message.js | 164 +++++++++++++++ src/zoom-recaps-to-slack/gate.js | 23 ++ src/zoom-recaps-to-slack/read-raw-body.js | 5 + src/zoom-recaps-to-slack/reset-a.js | 1 + src/zoom-recaps-to-slack/reset-b.js | 1 + src/zoom-recaps-to-slack/verify-zoom.js | 34 +++ 28 files changed, 1200 insertions(+) create mode 100644 .github/workflows/check-code-nodes.yml create mode 100644 scripts/code-nodes.js create mode 100644 src/governance/isc-gdrive/build-actual-structure.js create mode 100644 src/governance/isc-gdrive/check-missing-folders.js create mode 100644 src/governance/isc-gdrive/collect-existing-folder-descriptions.js create mode 100644 src/governance/isc-gdrive/flatten-folders-to-create.js create mode 100644 src/governance/isc-gdrive/set-missing-folders.js create mode 100644 src/new-member-introduction/slack-welcome-message-block-kit.js create mode 100644 src/send-bulk-dm/collect-members.js create mode 100644 src/send-bulk-dm/init-pagination.js create mode 100644 src/send-bulk-dm/output-all-members.js create mode 100644 src/summit/summit-keynote-reachout/collect-members.js create mode 100644 src/summit/summit-keynote-reachout/init-pagination.js create mode 100644 src/summit/summit-keynote-reachout/output-all-members.js create mode 100644 src/working-group-roles/isc-crier/build-slack-blocks.js create mode 100644 src/zoom-recaps-to-slack/apply-filter.js create mode 100644 src/zoom-recaps-to-slack/apply-full-notes.js create mode 100644 src/zoom-recaps-to-slack/attach-fields.js create mode 100644 src/zoom-recaps-to-slack/build-candidates.js create mode 100644 src/zoom-recaps-to-slack/format-full-notes.js create mode 100644 src/zoom-recaps-to-slack/format-message.js create mode 100644 src/zoom-recaps-to-slack/gate.js create mode 100644 src/zoom-recaps-to-slack/read-raw-body.js create mode 100644 src/zoom-recaps-to-slack/reset-a.js create mode 100644 src/zoom-recaps-to-slack/reset-b.js create mode 100644 src/zoom-recaps-to-slack/verify-zoom.js diff --git a/.github/workflows/check-code-nodes.yml b/.github/workflows/check-code-nodes.yml new file mode 100644 index 0000000..0110aaa --- /dev/null +++ b/.github/workflows/check-code-nodes.yml @@ -0,0 +1,22 @@ +name: Check Code-node source matches workflow JSON + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Check + run: node scripts/code-nodes.js check diff --git a/Makefile b/Makefile index 06db58d..33b238a 100644 --- a/Makefile +++ b/Makefile @@ -2,3 +2,18 @@ .PHONY: validate-json validate-json: find nodes -name '*.json' -exec python3 -c 'import json,sys; f=sys.argv[1]; json.load(open(f)); print("Valid:", f)' {} \; + +# Write the Code-node JavaScript in src/ into the workflow JSON under nodes/ +.PHONY: build +build: + node scripts/code-nodes.js build + +# Fail if the workflow JSON under nodes/ differs from what build would write +.PHONY: check +check: + node scripts/code-nodes.js check + +# Rewrite src/ from each Code node's jsCode, removing files whose node is gone +.PHONY: extract +extract: + node scripts/code-nodes.js extract diff --git a/USAGE.md b/USAGE.md index df30f97..d180dca 100644 --- a/USAGE.md +++ b/USAGE.md @@ -16,6 +16,24 @@ Publishing replaces the workflow's name, nodes, connections, settings, and stati The Action reads the API key from the `N8N_API_KEY` repository secret. +## Editing a Code node's JavaScript + +Each Code node's JavaScript lives in its own file under `src/`, so a pull request shows a code change as ordinary lines of JavaScript. +A Code node's file is `src///.js`, with each name lowercased and every run of other characters turned into a hyphen. +The code runs as the body of an n8n Code node, so a top-level `return` and n8n's built-in globals are valid there even where an editor marks them as errors. + +To change a Code node: + +1. Edit its file under `src/`. +2. Run `make build` (or `node scripts/code-nodes.js build`), which writes the code into the workflow JSON under `nodes/` and changes only the edited node's `jsCode` line. +3. Commit both the `.js` file and the workflow JSON. + +The workflow JSON stays committed because it is what publishing sends to n8n Cloud. +The `Check Code-node source matches workflow JSON` GitHub Action fails a pull request whose workflow JSON differs from what `make build` writes from `src/`; run `make check` to see the same result locally. + +When a workflow comes from an export of the n8n editor, or gains, loses, or renames a Code node, run `make extract` to rewrite `src/` from the workflow JSON. +Extract writes one file per Code node, removes files whose node is gone, and stops with an error if building from those files would not reproduce the workflow JSON byte for byte. + ## Credential errors (e.g. “does not exist for type …”) n8n stores credentials by **ID** on the server. If you see `Credential with ID "…" does not exist for type "googleDriveOAuth2Api"` on a node such as **Get All Folders**: diff --git a/scripts/code-nodes.js b/scripts/code-nodes.js new file mode 100644 index 0000000..7432fd7 --- /dev/null +++ b/scripts/code-nodes.js @@ -0,0 +1,197 @@ +#!/usr/bin/env node + +// Keeps each workflow's Code-node JavaScript in its own .js file under src/ +// and writes it back into the workflow JSON under nodes/. +// +// node scripts/code-nodes.js build write src/**/*.js into nodes/**/*.json +// node scripts/code-nodes.js check exit 1 if nodes/ differs from what build would write +// node scripts/code-nodes.js extract rewrite src/ from each Code node's jsCode, removing files whose node is gone +// +// A Code node's source lives at src///.js, +// where each slug is the name lowercased with every run of non-alphanumeric characters turned into a hyphen. +// Build rewrites only the jsCode string of a node whose code changed, so the rest of +// the JSON stays byte-for-byte as it was and a diff shows only the changed node. + +const fs = require('fs'); +const path = require('path'); + +const ROOT = path.resolve(__dirname, '..'); +const NODES_DIR = path.join(ROOT, 'nodes'); +const SRC_DIR = path.join(ROOT, 'src'); + +function walk(dir, ext) { + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const p = path.join(dir, entry.name); + if (entry.isDirectory()) return walk(p, ext); + return p.endsWith(ext) ? [p] : []; + }).sort(); +} + +function slug(name) { + return name + .normalize('NFKD') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +function rel(p) { + return path.relative(ROOT, p).split(path.sep).join('/'); +} + +// Finds every "jsCode": "..." string in the raw JSON text, in document order, +// returning where each string literal starts and ends so it can be replaced in place. +function findJsCodeLiterals(raw) { + const found = []; + const key = /"jsCode"\s*:\s*"/g; + let m; + while ((m = key.exec(raw)) !== null) { + if (m.index > 0 && raw[m.index - 1] === '\\') continue; + const start = m.index + m[0].length - 1; + let i = start + 1; + while (raw[i] !== '"') { + if (raw[i] === '\\') i++; + i++; + if (i >= raw.length) throw new Error('unterminated jsCode string'); + } + found.push({ start, end: i + 1, value: JSON.parse(raw.slice(start, i + 1)) }); + key.lastIndex = i + 1; + } + return found; +} + +// Loads one workflow and pairs each Code node with its jsCode literal in the raw text. +function loadWorkflow(file) { + const raw = fs.readFileSync(file, 'utf8'); + const workflow = JSON.parse(raw); + const codeNodes = (workflow.nodes || []).filter( + (n) => n.parameters && typeof n.parameters.jsCode === 'string' + ); + const literals = findJsCodeLiterals(raw); + if (literals.length !== codeNodes.length) { + throw new Error(`${rel(file)}: found ${literals.length} jsCode strings for ${codeNodes.length} Code nodes`); + } + + const workflowDir = path.join( + SRC_DIR, + path.relative(NODES_DIR, path.dirname(file)), + slug(path.basename(file, '.json')) + ); + const seen = new Map(); + const nodes = codeNodes.map((node, i) => { + if (literals[i].value !== node.parameters.jsCode) { + throw new Error(`${rel(file)}: jsCode strings are not in node order near "${node.name}"`); + } + const srcFile = path.join(workflowDir, `${slug(node.name)}.js`); + if (seen.has(srcFile)) { + throw new Error(`${rel(file)}: nodes "${seen.get(srcFile)}" and "${node.name}" both map to ${rel(srcFile)}; rename one`); + } + seen.set(srcFile, node.name); + return { name: node.name, code: node.parameters.jsCode, srcFile, literal: literals[i] }; + }); + return { file, raw, nodes }; +} + +function loadAll() { + return walk(NODES_DIR, '.json').map(loadWorkflow); +} + +// A .js file holds the code plus one closing newline, so editors that add a final +// newline leave the code unchanged. Line endings are normalized so a Windows +// checkout builds the same JSON as Linux CI. +function toSource(code) { + return code + '\n'; +} + +function fromSource(text) { + return text.replace(/\r\n/g, '\n').replace(/\n$/, ''); +} + +// Returns the workflow's raw text with every changed node's jsCode replaced. +function render(workflow, codeFor) { + let out = ''; + let pos = 0; + for (const node of workflow.nodes) { + const code = codeFor(node); + if (code === node.code) continue; + out += workflow.raw.slice(pos, node.literal.start) + JSON.stringify(code); + pos = node.literal.end; + } + return out + workflow.raw.slice(pos); +} + +function readSources(workflows) { + const errors = []; + const expected = new Set(); + for (const wf of workflows) { + for (const node of wf.nodes) { + expected.add(node.srcFile); + if (!fs.existsSync(node.srcFile)) { + errors.push(`${rel(wf.file)}: Code node "${node.name}" has no source file ${rel(node.srcFile)} (run extract)`); + } + } + } + for (const f of walk(SRC_DIR, '.js')) { + if (!expected.has(f)) errors.push(`${rel(f)} matches no Code node in nodes/`); + } + if (errors.length) { + errors.forEach((e) => console.error(`Error: ${e}`)); + process.exit(1); + } +} + +function build(write) { + const workflows = loadAll(); + readSources(workflows); + const stale = []; + for (const wf of workflows) { + const out = render(wf, (node) => fromSource(fs.readFileSync(node.srcFile, 'utf8'))); + if (out === wf.raw) continue; + stale.push(rel(wf.file)); + if (write) fs.writeFileSync(wf.file, out); + } + if (write) { + console.log(stale.length ? `Built ${stale.join(', ')}` : 'Workflow JSON already matches src/.'); + return; + } + if (stale.length) { + stale.forEach((f) => console.error(`Error: ${f} does not match its src/ code; run "make build" and commit the result`)); + process.exit(1); + } + console.log('Workflow JSON matches src/.'); +} + +function extract() { + const workflows = loadAll(); + const written = new Set(); + for (const wf of workflows) { + for (const node of wf.nodes) { + // Build re-serializes jsCode with JSON.stringify, so check that the file extract is + // about to write would rebuild this node's jsCode literal byte for byte. + const rebuilt = JSON.stringify(fromSource(toSource(node.code))); + if (rebuilt !== wf.raw.slice(node.literal.start, node.literal.end)) { + throw new Error(`${rel(wf.file)}: build would not reproduce the jsCode of "${node.name}"`); + } + fs.mkdirSync(path.dirname(node.srcFile), { recursive: true }); + fs.writeFileSync(node.srcFile, toSource(node.code)); + written.add(node.srcFile); + } + } + for (const f of walk(SRC_DIR, '.js')) { + if (!written.has(f)) { + fs.unlinkSync(f); + console.log(`Removed ${rel(f)} (no matching Code node)`); + } + } + console.log(`Extracted ${written.size} Code nodes to src/.`); +} + +const command = process.argv[2]; +if (command === 'build') build(true); +else if (command === 'check') build(false); +else if (command === 'extract') extract(); +else { + console.error('Usage: node scripts/code-nodes.js build|check|extract'); + process.exit(1); +} diff --git a/src/governance/isc-gdrive/build-actual-structure.js b/src/governance/isc-gdrive/build-actual-structure.js new file mode 100644 index 0000000..1271217 --- /dev/null +++ b/src/governance/isc-gdrive/build-actual-structure.js @@ -0,0 +1,46 @@ +// Build hierarchical structure from flat list of folders +// Convert Google Drive folder structure to JSON matching the desired structure format + +const rootFolderId = $('Set Configuration').first().json.rootFolderId; +// HTTP Request shape: { files: [...] }. Google Drive Search: one item per folder. +const allFolders = Array.isArray($json.files) + ? $json.files + : $input.all().map((item) => item.json); + +console.log('Total folders found in Google Drive:', allFolders.length); + +// Build a map: parentId -> [children] +const childrenMap = new Map(); +for (const folder of allFolders) { + const parentId = folder.parents && folder.parents.length > 0 ? folder.parents[0] : rootFolderId; + if (!childrenMap.has(parentId)) { + childrenMap.set(parentId, []); + } + childrenMap.get(parentId).push({ + id: folder.id, + name: folder.name + }); +} + +console.log('Folders directly under root:', childrenMap.get(rootFolderId)?.length || 0); + +// Build tree structure starting directly from rootFolderId +// Function to recursively build tree structure +function buildTree(parentId) { + const children = childrenMap.get(parentId) || []; + return children.map(child => { + const node = { name: child.name }; + const childChildren = buildTree(child.id); + if (childChildren.length > 0) { + node.children = childChildren; + } + return node; + }); +} + +// Build tree starting from rootFolderId (which is now a folder, not a drive root) +const actualStructure = buildTree(rootFolderId); + +console.log('Actual structure built:', JSON.stringify(actualStructure, null, 2)); + +return [{ json: { actualStructure, allFolders } }]; diff --git a/src/governance/isc-gdrive/check-missing-folders.js b/src/governance/isc-gdrive/check-missing-folders.js new file mode 100644 index 0000000..5394bb7 --- /dev/null +++ b/src/governance/isc-gdrive/check-missing-folders.js @@ -0,0 +1,24 @@ +const folders = $json.folders || []; + +function collectMissing(structure, parentPath = "") { + let missing = []; + for (const node of structure) { + const currentPath = parentPath ? `${parentPath}/${node.name}` : node.name; + if (node.exists === false) { + missing.push(currentPath); + } + if (node.children && node.children.length > 0) { + missing = missing.concat(collectMissing(node.children, currentPath)); + } + } + return missing; +} + +const missingList = collectMissing(folders); +const missingCount = missingList.length; +const missingFoldersText = missingList.join("\n"); + +console.log("Missing folders:", missingCount); +console.log("Missing folders list:", missingFoldersText); + +return [{ json: { folders, missingCount, hasMissing: missingCount > 0, missingFoldersText } }]; diff --git a/src/governance/isc-gdrive/collect-existing-folder-descriptions.js b/src/governance/isc-gdrive/collect-existing-folder-descriptions.js new file mode 100644 index 0000000..6760efa --- /dev/null +++ b/src/governance/isc-gdrive/collect-existing-folder-descriptions.js @@ -0,0 +1,38 @@ +const folders = $json.folders || []; +const allFolders = $('Build Actual Structure').first().json.allFolders || []; +const rootFolderId = $('Set Configuration').first().json.rootFolderId; + +const folderLookup = new Map(); +for (const f of allFolders) { + const parentId = f.parents && f.parents.length > 0 ? f.parents[0] : rootFolderId; + folderLookup.set(`${parentId}::${f.name}`, f.id); +} + +const results = []; + +function collect(nodes, parentFolderId) { + for (const node of nodes) { + const key = `${parentFolderId}::${node.name}`; + const folderId = folderLookup.get(key); + + if (folderId && node.description) { + results.push({ + json: { + folderId, + name: node.name, + description: node.description + } + }); + } + + if (folderId && node.children && node.children.length > 0) { + collect(node.children, folderId); + } + } +} + +collect(folders, rootFolderId); + +console.log(`Found ${results.length} existing folders with descriptions to update`); + +return results.length > 0 ? results : []; diff --git a/src/governance/isc-gdrive/flatten-folders-to-create.js b/src/governance/isc-gdrive/flatten-folders-to-create.js new file mode 100644 index 0000000..26abcb1 --- /dev/null +++ b/src/governance/isc-gdrive/flatten-folders-to-create.js @@ -0,0 +1,149 @@ +// Flatten structure and produce a list of folders to create for THIS run. +// - Only output folders where `exists === false` AND the parent already exists. +// - Compute parentFolderId from the current Drive state (Build Actual Structure). +// +// On first run: only top-level folders are created. +// On second run: their children are created. +// On third run: grandchildren, etc. +// +// You keep running the workflow until it logs "0 folders to create". + +// --- CONFIG & INPUT --- + +const rootFolderId = $('Set Configuration').first().json.rootFolderId; +const mainFolderId = rootFolderId; + +console.log('Using rootFolderId as mainFolderId:', mainFolderId); + +// This comes from "Check Missing Folders" +const folderStatusTree = $('Check Missing Folders').first().json.folders || []; + +// From "Build Actual Structure" (current Drive state) +const actualStructure = $('Build Actual Structure').first().json.actualStructure || []; +const allFolders = $('Build Actual Structure').first().json.allFolders || []; + +console.log('Actual structure nodes:', actualStructure.length); +console.log('Total folders in allFolders:', allFolders.length); + +// --- BUILD path -> folderId MAP FROM CURRENT DRIVE STATE --- + +// We'll reconstruct full paths like "00 – Governance/Charter" +const pathToId = new Map(); + +function buildPathMap(structure, parentPath = '', parentId = mainFolderId) { + for (const node of structure) { + const currentPath = parentPath ? `${parentPath}/${node.name}` : node.name; + + // Find the matching folder from allFolders by name + parentId + const folder = allFolders.find(f => { + const fParentId = f.parents && f.parents.length > 0 ? f.parents[0] : rootFolderId; + return f.name === node.name && fParentId === parentId; + }); + + if (folder) { + pathToId.set(currentPath, folder.id); + // Recurse into children + if (node.children && node.children.length > 0) { + buildPathMap(node.children, currentPath, folder.id); + } + } + } +} + +buildPathMap(actualStructure); + +console.log('Existing paths in Drive:'); +for (const [p, id] of pathToId.entries()) { + console.log(` ${p} -> ${id}`); +} + +// --- FLATTEN DESIRED STRUCTURE (with exists flags) --- +// We only output folders where: +// - node.exists === false +// - the parent "exists" right now (either root or in pathToId / actualStructure) + +function flattenForCreation(structure, parentPath = '', parentName = null, depth = 0, parentExists = true) { + const result = []; + + for (const node of structure) { + const currentPath = parentPath ? `${parentPath}/${node.name}` : node.name; + const thisExists = node.exists === true; + + // Decide if THIS node should be created in this run + // Only when it doesn't exist yet, and its parent exists. + if (!thisExists && parentExists) { + let parentFolderId; + + if (!parentPath) { + // Top-level folder under the main/root folder + parentFolderId = mainFolderId; + } else { + // Parent is some subfolder; look it up by its full path + parentFolderId = pathToId.get(parentPath) || mainFolderId; + } + + console.log( + `Scheduling create: "${currentPath}" ` + + `(depth ${depth}, parentPath="${parentPath}", parentFolderId=${parentFolderId})` + ); + + result.push({ + name: node.name, + description: node.description || '', + path: currentPath, + parentPath, + parentName, + depth, + parentFolderId, + }); + } else { + console.log( + `Skipping for now: "${currentPath}" (exists=${thisExists}, parentExists=${parentExists})` + ); + } + + // Children: their parent "exists" if: + // - this node already exists in Drive (thisExists === true), OR + // - we have a path->id entry for it (i.e., it existed before this run). + const childParentExists = thisExists || pathToId.has(currentPath); + + if (node.children && node.children.length > 0) { + const childResults = flattenForCreation( + node.children, + currentPath, + node.name, + depth + 1, + childParentExists, + ); + result.push(...childResults); + } + } + + return result; +} + +const flattened = flattenForCreation(folderStatusTree); + +// Sort by depth so parents of this batch are before children of this batch +flattened.sort((a, b) => a.depth - b.depth); + +console.log(`\nFound ${flattened.length} folders to create in THIS run:`); +flattened.forEach(f => + console.log( + ` [depth ${f.depth}] ${f.path} (parentPath="${f.parentPath}", parentFolderId=${f.parentFolderId})`, + ), +); + +// Output each folder as a separate item +const outputItems = flattened.map(folder => ({ + json: { + ...folder, + mainFolderId, + rootFolderId, + }, +})); + +console.log(`\n=== OUTPUT: Returning ${outputItems.length} items ===`); + +return outputItems; + diff --git a/src/governance/isc-gdrive/set-missing-folders.js b/src/governance/isc-gdrive/set-missing-folders.js new file mode 100644 index 0000000..9f03773 --- /dev/null +++ b/src/governance/isc-gdrive/set-missing-folders.js @@ -0,0 +1,119 @@ +// Compare desired structure with actual structure +// Include ALL folders with exists: true/false field + +// Decode HTML entities that n8n expression rendering may introduce +function decodeHtmlEntities(str) { + return str + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'"); +} + +// Recursively decode HTML entities in all name fields +function decodeNames(nodes) { + return nodes.map(node => { + const decoded = { ...node, name: decodeHtmlEntities(node.name) }; + if (decoded.children && decoded.children.length > 0) { + decoded.children = decodeNames(decoded.children); + } + return decoded; + }); +} + +const rawDesired = typeof $('Set Configuration').first().json.desiredStructure === 'string' + ? JSON.parse($('Set Configuration').first().json.desiredStructure) + : $('Set Configuration').first().json.desiredStructure; + +const desiredStructure = decodeNames(rawDesired); + +const actualStructure = $json.actualStructure || []; + +console.log('Desired structure:', JSON.stringify(desiredStructure, null, 2)); +console.log('Actual structure:', JSON.stringify(actualStructure, null, 2)); + +// Build a lookup map: parentName -> Map +// This allows us to check if a folder exists by its name and parent context +function buildNameMap(structure, parentName = null) { + const nameMap = new Map(); // parentName -> Set + + function processNode(node, parent) { + const parentKey = parent || 'ROOT'; + if (!nameMap.has(parentKey)) { + nameMap.set(parentKey, new Set()); + } + nameMap.get(parentKey).add(node.name); + + if (node.children && node.children.length > 0) { + for (const child of node.children) { + processNode(child, node.name); + } + } + } + + for (const node of structure) { + processNode(node, null); + } + + return nameMap; +} + +const actualNameMap = buildNameMap(actualStructure); + +console.log('Actual name map:', JSON.stringify( + Array.from(actualNameMap.entries()).map(([k, v]) => [k, Array.from(v)]), + null, 2 +)); + +// Function to check if a folder exists by name and parent +function folderExists(folderName, parentName = null) { + const parentKey = parentName || 'ROOT'; + const exists = actualNameMap.has(parentKey) && actualNameMap.get(parentKey).has(folderName); + + // Debug: log what we're checking + if (!exists) { + console.log(` Folder NOT found: name="${folderName}", parent="${parentKey}"`); + if (actualNameMap.has(parentKey)) { + console.log(` Available children in ${parentKey}:`, Array.from(actualNameMap.get(parentKey))); + } else { + console.log(` Parent ${parentKey} not found in actual structure`); + } + } else { + console.log(` ✓ Folder found: name="${folderName}", parent="${parentKey}"`); + } + + return exists; +} + +// Function to recursively check folders and add exists field +function checkFolders(desiredNode, parentName = null) { + const exists = folderExists(desiredNode.name, parentName); + + console.log(`Checking folder: ${desiredNode.name}, parent: ${parentName || 'ROOT'}, exists: ${exists}`); + + const result = { + name: desiredNode.name, + exists: exists + }; + + if (desiredNode.description) { + result.description = desiredNode.description; + } + + // Check children - always include all children + if (desiredNode.children && desiredNode.children.length > 0) { + result.children = desiredNode.children.map(child => + checkFolders(child, desiredNode.name) + ); + } + + return result; +} + +// Check all folders +const folderStatus = desiredStructure.map(node => checkFolders(node)); + +console.log('Folder status:', JSON.stringify(folderStatus, null, 2)); + +return [{ json: { folders: folderStatus } }]; diff --git a/src/new-member-introduction/slack-welcome-message-block-kit.js b/src/new-member-introduction/slack-welcome-message-block-kit.js new file mode 100644 index 0000000..3948729 --- /dev/null +++ b/src/new-member-introduction/slack-welcome-message-block-kit.js @@ -0,0 +1,63 @@ +// Edit the blocks array below to match Slack Block Kit. Copy the whole blocks array +// and paste into https://app.slack.com/block-kit-builder/ to preview. +// block_kit_builder_url in the output opens the builder with this payload. +const displayName = $input.first().json.new_user_display_name || 'there'; +const blocks = [ + { + type: 'section', + text: { + type: 'mrkdwn', + text: `*Hey ${displayName}!*\n\nWelcome to the InnerSource Commons! It's so cool you're here! 🎉\n\nThis is a global community of practitioners, researchers, and curious minds all exploring how open collaboration works inside organizations.` + } + }, + { type: 'divider' }, + { + type: 'section', + text: { + type: 'mrkdwn', + text: "👋 *Head over to <#C0867TAF63H|newcomers> and tell us a little about yourself, or choose how you'd like to get started:*" + } + }, + { + type: 'actions', + elements: [ + { type: 'button', text: { type: 'plain_text', text: '📖 Quick Start Guide', emoji: true }, url: 'https://innersourcecommons.org/community/quick-start-guide/' }, + { type: 'button', text: { type: 'plain_text', text: '📅 Join a Meeting', emoji: true }, url: 'https://innersourcecommons.org/community/calendar/' }, + { type: 'button', text: { type: 'plain_text', text: '🏢 Pattern Library', emoji: true }, url: 'https://patterns.innersourcecommons.org/' } + ] + }, + { + type: 'section', + text: { + type: 'mrkdwn', + text: '🌍 Join a Regional Community: <#C07MXDSG2P8|africa> <#C03M546NR16|japan>' + } + }, + { type: 'divider' }, + { + type: 'section', + text: { + type: 'mrkdwn', + text: '🔎 *Explore channels that match your interests:*\n\n• <#C2EFRTS6A|innersource-patterns> — practical patterns for making innersource work\n• <#C046MD5R5RT|local-community> — find or start a gathering near you\n• <#C04DT6NQX7G|ispo-working-group> — dive into standards and best practices' + } + }, + { type: 'divider' }, + { + type: 'section', + text: { + type: 'mrkdwn', + text: '💬 Looking for something else? Ask in <#C04PXKRN4|general>, and the community will be happy to help!' + } + } +]; +const payload = { blocks }; +const blockKitBuilderUrl = 'https://app.slack.com/block-kit-builder/T04PXKRM0#' + encodeURIComponent(JSON.stringify(payload)); +return $input.all().map(item => ({ + json: { + ...item.json, + blocks, + blocks_json: JSON.stringify(payload, null, 2), + block_kit_builder_url: blockKitBuilderUrl + } +})); + diff --git a/src/send-bulk-dm/collect-members.js b/src/send-bulk-dm/collect-members.js new file mode 100644 index 0000000..9dda47b --- /dev/null +++ b/src/send-bulk-dm/collect-members.js @@ -0,0 +1,7 @@ +const staticData = $getWorkflowStaticData('global'); +const response = $input.first().json; +if (response.members) { + staticData.allMembers.push(...response.members); +} +const nextCursor = response.response_metadata?.next_cursor || ''; +return [{ json: { cursor: nextCursor } }]; diff --git a/src/send-bulk-dm/init-pagination.js b/src/send-bulk-dm/init-pagination.js new file mode 100644 index 0000000..eaaa09d --- /dev/null +++ b/src/send-bulk-dm/init-pagination.js @@ -0,0 +1,3 @@ +const staticData = $getWorkflowStaticData('global'); +staticData.allMembers = []; +return [{ json: { cursor: '' } }]; diff --git a/src/send-bulk-dm/output-all-members.js b/src/send-bulk-dm/output-all-members.js new file mode 100644 index 0000000..1e2a555 --- /dev/null +++ b/src/send-bulk-dm/output-all-members.js @@ -0,0 +1,3 @@ +const staticData = $getWorkflowStaticData('global'); +const allMembers = staticData.allMembers || []; +return [{ json: { members: allMembers } }]; diff --git a/src/summit/summit-keynote-reachout/collect-members.js b/src/summit/summit-keynote-reachout/collect-members.js new file mode 100644 index 0000000..9dda47b --- /dev/null +++ b/src/summit/summit-keynote-reachout/collect-members.js @@ -0,0 +1,7 @@ +const staticData = $getWorkflowStaticData('global'); +const response = $input.first().json; +if (response.members) { + staticData.allMembers.push(...response.members); +} +const nextCursor = response.response_metadata?.next_cursor || ''; +return [{ json: { cursor: nextCursor } }]; diff --git a/src/summit/summit-keynote-reachout/init-pagination.js b/src/summit/summit-keynote-reachout/init-pagination.js new file mode 100644 index 0000000..eaaa09d --- /dev/null +++ b/src/summit/summit-keynote-reachout/init-pagination.js @@ -0,0 +1,3 @@ +const staticData = $getWorkflowStaticData('global'); +staticData.allMembers = []; +return [{ json: { cursor: '' } }]; diff --git a/src/summit/summit-keynote-reachout/output-all-members.js b/src/summit/summit-keynote-reachout/output-all-members.js new file mode 100644 index 0000000..1e2a555 --- /dev/null +++ b/src/summit/summit-keynote-reachout/output-all-members.js @@ -0,0 +1,3 @@ +const staticData = $getWorkflowStaticData('global'); +const allMembers = staticData.allMembers || []; +return [{ json: { members: allMembers } }]; diff --git a/src/working-group-roles/isc-crier/build-slack-blocks.js b/src/working-group-roles/isc-crier/build-slack-blocks.js new file mode 100644 index 0000000..1392163 --- /dev/null +++ b/src/working-group-roles/isc-crier/build-slack-blocks.js @@ -0,0 +1,20 @@ +const item = $input.first().json; +const d = item.utcDate; +const q = item.query; +const blocks = { + blocks: [ + { type: 'section', text: { type: 'mrkdwn', text: ` Reminder: InnerSource Working Group call happens ${d.dayofweekname} at ${q.time} UTC :tada:\n\nThis is an excellent meeting for newcomers looking to learn about InnerSource. All are welcome to join!` } }, + { type: 'divider' }, + { type: 'section', text: { type: 'mrkdwn', text: `*This meeting's topic:*\n\n${q.topic}` } }, + { type: 'divider' }, + { type: 'section', fields: [ + { type: 'mrkdwn', text: `:spiral_calendar_pad: *Date:*\n${d.dayofweekname}, ${d.monthname} ${d.ordinal}` }, + { type: 'mrkdwn', text: ':alarm_clock: *Time:*\nMultiple time zones below' } + ] }, + { type: 'section', text: { type: 'mrkdwn', text: `*Time Zones:*\n${d.timeZonesText}` } }, + { type: 'divider' }, + { type: 'section', text: { type: 'mrkdwn', text: `:link: <${q.meeting_notes_url}>\n:link: ` } }, + { type: 'actions', elements: [ { type: 'button', text: { type: 'plain_text', text: 'Join Meeting', emoji: true }, url: 'https://us06web.zoom.us/j/84987611486?pwd=Biw6cc9UwWI6FrM51Ugox10sClIP6n.1', style: 'danger' } ] } + ] +}; +return [{ json: { ...item, blocks } }]; diff --git a/src/zoom-recaps-to-slack/apply-filter.js b/src/zoom-recaps-to-slack/apply-filter.js new file mode 100644 index 0000000..61a9a30 --- /dev/null +++ b/src/zoom-recaps-to-slack/apply-filter.js @@ -0,0 +1,20 @@ +// Replace recap + nextSteps with the InnerSource-Commons-only cleaned versions from the filter. +// Privacy-safe: if the filter didn't return a usable result, SKIP posting rather than falling back +// to the raw (unfiltered) summary. And if nothing ISC-related survived, there is nothing to post. +const resp = $json || {}; +const rec = $('Gate').item.json; +let recap = null, nextSteps = null; +try { + const text = (resp.content || []).filter(b => b.type === 'text').map(b => b.text).join(''); + const m = text.match(/\{[\s\S]*\}/); + if (m) { + const parsed = JSON.parse(m[0]); + if (typeof parsed.recap === 'string') recap = parsed.recap; + if (Array.isArray(parsed.nextSteps)) nextSteps = parsed.nextSteps; + } +} catch (e) {} +if (recap === null || nextSteps === null) return []; +recap = recap.trim(); +if (!recap && nextSteps.length === 0) return []; +return [{ json: { ...rec, recap, nextSteps } }]; + diff --git a/src/zoom-recaps-to-slack/apply-full-notes.js b/src/zoom-recaps-to-slack/apply-full-notes.js new file mode 100644 index 0000000..0e804b0 --- /dev/null +++ b/src/zoom-recaps-to-slack/apply-full-notes.js @@ -0,0 +1,97 @@ +// Take Claude's cleaned full-notes text, resolve member names to @-mentions, chunk into Block Kit. +// Mentions are gated to actual members of the target channel (same rule as the main recap): +// only a name resolving to a channel member is tagged; external names stay plain. +const resp = $json || {}; +const src = $('Format Full Notes').item.json; +// Privacy-safe: use only the filter's InnerSource-Commons-only output. If it returned nothing usable +// (filter failed, or nothing ISC-related remained), skip the thread rather than posting raw notes. +let notes = null; +try { + const t = (resp.content || []).filter(b => b.type === 'text').map(b => b.text).join(''); + notes = t.trim(); +} catch (e) { notes = null; } +if (!notes) return []; +const memberIds = new Set($('Slack: conversations.members').all().flatMap(i => (i.json.members) || [])); +const members = $('Slack: users.list').all() + .flatMap(i => (i.json.members) || []) + .filter(m => memberIds.has(m.id) && !m.deleted && !m.is_bot && m.id !== 'USLACKBOT'); +const norm = x => (x || '').toString().trim().toLowerCase(); +const ALIAS = { russell: 'russ' }; +const canon = f => ALIAS[norm(f)] || norm(f); +const aliasVariants = {}; +for (const [variant, c] of Object.entries(ALIAS)) (aliasVariants[c] = aliasVariants[c] || []).push(variant); +// Common words that show up in notes prose but are also, occasionally, someone's junk Slack name. +const COMMON_WORDS = new Set(['name', 'names', 'team', 'teams', 'board', 'group', 'groups', 'call', 'calls', 'meeting', 'meetings', 'note', 'notes', 'update', 'updates', 'staff', 'work', 'works', 'next', 'step', 'steps', 'item', 'items', 'all', 'new', 'lead', 'leads', 'chair', 'member', 'members', 'working', 'community', 'summit', 'project', 'projects', 'plan', 'plans', 'goal', 'goals', 'review', 'agenda', 'action', 'actions', 'report', 'reports', 'week', 'weeks', 'day', 'days', 'time', 'times', 'page', 'pages', 'doc', 'docs', 'content', 'video', 'videos', 'deck', 'issue', 'issues', 'code', 'user', 'users', 'test', 'admin', 'guest', 'welcome', 'thanks', 'hello']); +const byName = {}, byFirstC = {}; +for (const m of members) { + const p = m.profile || {}; + for (const n of [p.real_name, p.display_name, m.real_name, m.name, p.real_name_normalized, p.display_name_normalized]) { + const k = norm(n); + if (k && k.includes(' ') && !(k in byName)) byName[k] = m.id; + } + for (const n of [p.real_name, m.real_name, p.display_name, m.name]) { + const c = canon((n || '').split(/[.\s_]+/)[0]); + if (c && c.length >= 3 && !COMMON_WORDS.has(c)) (byFirstC[c] = byFirstC[c] || new Set()).add(m.id); + } +} +const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +function lev(a, b) { + const m = a.length, n = b.length; + if (!m) return n; if (!n) return m; + const d = Array.from({ length: m + 1 }, (_, i) => [i, ...Array(n).fill(0)]); + for (let j = 0; j <= n; j++) d[0][j] = j; + for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); + return d[m][n]; +} +function fuzzyFirstId(tok) { + const t = canon(tok); + if (t.length < 5) return null; + let hit = null; + for (const [c, set] of Object.entries(byFirstC)) { + if (c.length < 5 || set.size !== 1) continue; + if (lev(t, c) <= 1) { const id = [...set][0]; if (hit && hit !== id) return null; hit = id; } + } + return hit; +} +function resolveProse(text) { + let out = text || ''; + for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) { + out = out.replace(new RegExp('\\b' + esc(name) + '\\b', 'gi'), '<@' + byName[name] + '>'); + } + for (const [c, set] of Object.entries(byFirstC)) { + if (set.size !== 1) continue; + const id = [...set][0]; + for (const t of [c, ...(aliasVariants[c] || [])]) out = out.replace(new RegExp('\\b' + esc(t) + '\\b', 'gi'), '<@' + id + '>'); + } + out = out.replace(/\b[A-Z][a-z]{4,}\b/g, (w) => { const id = fuzzyFirstId(w); return id ? '<@' + id + '>' : w; }); + return out; +} +// Chatham House series: never tag or name a participant. Any channel member's name that survived the +// anonymizing filter is replaced with a neutral stand-in (a backstop - the filter already strips names). +function scrub(text) { + let out = text || ''; + const anon = (m, poss, at, str) => (/(^|[.!?:*\n]\s*)$/.test(str.slice(0, at)) ? 'A' : 'a') + ' participant' + (poss || ''); + for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) { + out = out.replace(new RegExp('\\b' + esc(name) + '(\'s)?\\b', 'gi'), anon); + } + for (const c of Object.keys(byFirstC)) { + for (const t of [c, ...(aliasVariants[c] || [])]) { + out = out.replace(new RegExp('\\b' + esc(t[0].toUpperCase() + t.slice(1)) + '(\'s)?\\b', 'g'), anon); + } + } + return out; +} +function sectionBlocks(text) { + const out = []; let cur = ''; + for (const line of (text || '').split('\n')) { + if ((cur + '\n' + line).length > 2900) { if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } }); cur = line; } + else { cur = cur ? cur + '\n' + line : line; } + } + if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } }); + return out; +} +notes = src.chathamHouse ? scrub(notes) : resolveProse(notes); +const blocks = [{ type: 'section', text: { type: 'mrkdwn', text: '*Full notes*' } }].concat(sectionBlocks(notes)).slice(0, 48); +return [{ json: { channel: src.channel, threadTs: src.threadTs, blocks } }]; + diff --git a/src/zoom-recaps-to-slack/attach-fields.js b/src/zoom-recaps-to-slack/attach-fields.js new file mode 100644 index 0000000..3730531 --- /dev/null +++ b/src/zoom-recaps-to-slack/attach-fields.js @@ -0,0 +1,5 @@ +// Config Lookup produced the channel row (or nothing => not in allowlist, drop). +const channel = $json.channel; +if (!channel) return []; +const cand = $('Build Candidates').item.json; +return [{ json: { ...cand, channel } }]; diff --git a/src/zoom-recaps-to-slack/build-candidates.js b/src/zoom-recaps-to-slack/build-candidates.js new file mode 100644 index 0000000..cd39cad --- /dev/null +++ b/src/zoom-recaps-to-slack/build-candidates.js @@ -0,0 +1,101 @@ +// Pick the one meeting to post this run: the newest UNPOSTED occurrence of any configured meeting +// (on a webhook run, of the triggering meeting only) whose summary is ready to post (see readyToPost). An occurrence with nothing to post - a room started +// and stopped in seconds, a summary Zoom never generated, a failed fetch - is skipped, never allowed to +// block the occurrences behind it. Calendar guardrail: a meeting headed for a PUBLIC channel +// must match a scheduled public-calendar event (same Zoom meeting id + weekday/time) - this stops a +// different meeting that borrowed the same Zoom room (e.g. a board meeting) from posting to a public +// channel. Meetings headed for PRIVATE channels post without that check. Emits 0 or 1 item. +const token = $('Get Zoom Token').first().json.access_token; + +const config = {}; +const chatham = {}; +for (const r of $('All Config').all()) { const j = r.json || {}; if (j.meetingId) { config[String(j.meetingId)] = j.channel; chatham[String(j.meetingId)] = j.chathamHouse === true; } } +const posted = new Set($('All Posted').all().map(r => (r.json || {}).occurrenceUuid).filter(Boolean)); + +// Channel privacy from the conversations.list side fetch; default to private (safe) if unknown. +const chans = $('Slack: conversations.list').all().flatMap(i => (i.json.channels) || []); +const isPrivateChannel = (name) => { const c = chans.find(x => '#' + x.name === name); return c ? !!c.is_private : true; }; + +// Public-calendar iCal text (fetched upstream, no auth). +const j = $('Public Calendar').first().json; +const ical = (j && (j.data || (typeof j === 'string' ? j : j.body))) || ''; +function matchesPublicEvent(icalText, meetingId, occurrenceIso) { + const text = (icalText || '').replace(/\r?\n[ \t]/g, ''); // unfold continuation lines + const events = text.split('BEGIN:VEVENT').slice(1); + const occ = new Date(occurrenceIso); + const occDate = occurrenceIso.slice(0, 10).replace(/-/g, ''); + const occWeekday = occ.getUTCDay(); + const occMin = occ.getUTCHours() * 60 + occ.getUTCMinutes(); + for (const e of events) { + if (!e.includes(String(meetingId))) continue; + const dt = (e.match(/DTSTART[^:]*:([0-9T]+Z?)/) || [])[1]; + if (!dt) continue; + if (dt.slice(0, 8) === occDate) return true; // concrete instance on the same date + if (/Z$/.test(dt)) { // recurring UTC slot: match weekday + time-of-day + const h = +dt.slice(9, 11), mi = +dt.slice(11, 13); + const evd = new Date(Date.UTC(+dt.slice(0, 4), +dt.slice(4, 6) - 1, +dt.slice(6, 8), h, mi)); + if (evd.getUTCDay() === occWeekday && Math.abs((h * 60 + mi) - occMin) <= 90) return true; + } + } + return false; +} + +// Flatten every summary across the paginated List Summaries responses. +const all = []; +for (const it of $('List Summaries').all()) for (const s of (((it.json || {}).summaries) || [])) all.push(s); + +// A webhook run handles only the meeting that triggered it, so two meetings finishing close together +// don't race for the same run. Verify Zoom only has output on the webhook path; the daily sweep never +// executes it, so reading it there throws and the sweep keeps considering every configured meeting. +let trigger = null; +try { trigger = $('Verify Zoom').first().json; } catch (e) { trigger = null; } +const triggerId = trigger && trigger.meetingId ? String(trigger.meetingId) : ''; +const triggerUuid = trigger && trigger.meetingUuid ? String(trigger.meetingUuid) : ''; + +// Every unposted occurrence of a configured meeting, newest first. +let eligible = all + .filter(s => config[String(s.meeting_id)] && !posted.has(s.meeting_uuid)) + .filter(s => !triggerId || String(s.meeting_id) === triggerId) + .sort((a, b) => new Date(b.meeting_start_time) - new Date(a.meeting_start_time)); +// Prefer the exact occurrence that triggered the webhook; if the list doesn't show it yet, fall back to +// the newest unposted occurrence of the same meeting. +if (triggerUuid && eligible.some(s => s.meeting_uuid === triggerUuid)) eligible = eligible.filter(s => s.meeting_uuid === triggerUuid); + +// Same test as the Gate (content present, summary not still being refined), asked here so an +// occurrence that fails it is passed over instead of ending the run. Any fetch error counts as not ready. +const COOLDOWN_MIN = 15; +const readyToPost = async (s) => { + try { + const d = await this.helpers.httpRequest({ + method: 'GET', + url: 'https://api.zoom.us/v2/meetings/' + encodeURIComponent(encodeURIComponent(s.meeting_uuid)) + '/meeting_summary', + headers: { Authorization: 'Bearer ' + token }, + json: true, + }); + if (!(d.summary_overview || (Array.isArray(d.next_steps) && d.next_steps.length))) return false; + const modIso = d.summary_last_modified_time || d.summary_created_time; + return !modIso || (Date.now() - new Date(modIso).getTime()) / 60000 >= COOLDOWN_MIN; + } catch (e) { return false; } +}; + +// Pick the newest that clears the guardrail and is ready. +let chosen = null; +for (const s of eligible) { + const channel = config[String(s.meeting_id)]; + // public channel + no matching public event -> a room-reuse; skip it, try the next. + if (!isPrivateChannel(channel) && !matchesPublicEvent(ical, s.meeting_id, s.meeting_start_time)) continue; + if (await readyToPost(s)) { chosen = s; break; } +} +if (!chosen) return []; + +return [{ json: { + meetingUuid: chosen.meeting_uuid, + meetingId: String(chosen.meeting_id), + topic: chosen.meeting_topic, + meetingStart: chosen.meeting_start_time, + channel: config[String(chosen.meeting_id)], + chathamHouse: !!chatham[String(chosen.meeting_id)], + occurrenceUuid: chosen.meeting_uuid, + token, +}}]; + diff --git a/src/zoom-recaps-to-slack/format-full-notes.js b/src/zoom-recaps-to-slack/format-full-notes.js new file mode 100644 index 0000000..4387d90 --- /dev/null +++ b/src/zoom-recaps-to-slack/format-full-notes.js @@ -0,0 +1,12 @@ +// Build the raw full-notes text from Zoom's detailed sections, plus the main post's thread ts. +const rec = $('Apply Filter').item.json; +const details = rec.summaryDetails || []; +const channel = $('Format Message').item.json.channel; +const post = $('Slack: chat.postMessage').item.json; +const ts = post && post.ts; +if (!details.length || !ts) return []; +const notesText = details + .map(d => '*' + (d.label || '').toString().trim() + '*\n' + (d.summary || '').toString().trim()) + .join('\n\n'); +return [{ json: { channel, threadTs: ts, notesText, chathamHouse: !!rec.chathamHouse } }]; + diff --git a/src/zoom-recaps-to-slack/format-message.js b/src/zoom-recaps-to-slack/format-message.js new file mode 100644 index 0000000..16e6a34 --- /dev/null +++ b/src/zoom-recaps-to-slack/format-message.js @@ -0,0 +1,164 @@ +// Resolve names to Slack @-mentions and build the Block Kit recap. +// Mentions are gated to ACTUAL MEMBERS of the target channel: a name is tagged only when +// it resolves to a Slack user who belongs to the channel this recap posts to. That tags every +// attendee who's in the channel (in prose and in action items) and leaves genuinely external +// people plain, and it disambiguates common names for free (e.g. among 9 "Jeff"s in the +// workspace, only the one in the channel gets the ping). +const rec = $('Skip If Already Posted').item.json; +const memberIds = new Set($('Slack: conversations.members').all().flatMap(i => (i.json.members) || [])); +const members = $('Slack: users.list').all() + .flatMap(i => (i.json.members) || []) + .filter(m => memberIds.has(m.id) && !m.deleted && !m.is_bot && m.id !== 'USLACKBOT'); +const norm = x => (x || '').toString().trim().toLowerCase(); +// Nickname families: a spelling on the left, when it appears in the text, resolves to a member +// whose first name is the canonical form on the right (lets "Russell" reach the member "Russ"). +const ALIAS = { russell: 'russ' }; +const canon = f => ALIAS[norm(f)] || norm(f); +const aliasVariants = {}; // canonical -> extra text spellings that should also match +for (const [variant, c] of Object.entries(ALIAS)) (aliasVariants[c] = aliasVariants[c] || []).push(variant); +// Common words that show up in recap prose but are also, occasionally, someone's junk Slack name +// (e.g. a user whose real name is literally "name"). Never treat these as a first name to tag. +const COMMON_WORDS = new Set(['name', 'names', 'team', 'teams', 'board', 'group', 'groups', 'call', 'calls', 'meeting', 'meetings', 'note', 'notes', 'update', 'updates', 'staff', 'work', 'works', 'next', 'step', 'steps', 'item', 'items', 'all', 'new', 'lead', 'leads', 'chair', 'member', 'members', 'working', 'community', 'summit', 'project', 'projects', 'plan', 'plans', 'goal', 'goals', 'review', 'agenda', 'action', 'actions', 'report', 'reports', 'week', 'weeks', 'day', 'days', 'time', 'times', 'page', 'pages', 'doc', 'docs', 'content', 'video', 'videos', 'deck', 'issue', 'issues', 'code', 'user', 'users', 'test', 'admin', 'guest', 'welcome', 'thanks', 'hello']); +const byName = {}; // full "first last" -> id (channel members only) +const byFirstC = {}; // canonical first name -> Set (channel members only) +for (const m of members) { + const p = m.profile || {}; + for (const n of [p.real_name, p.display_name, m.real_name, m.name, p.real_name_normalized, p.display_name_normalized]) { + const k = norm(n); + if (k && k.includes(' ') && !(k in byName)) byName[k] = m.id; + } + for (const n of [p.real_name, m.real_name, p.display_name, m.name]) { + const c = canon((n || '').split(/[.\s_]+/)[0]); + if (c && c.length >= 3 && !COMMON_WORDS.has(c)) (byFirstC[c] = byFirstC[c] || new Set()).add(m.id); + } +} +const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +// Levenshtein distance, used for a tight fuzzy match against the channel roster. +function lev(a, b) { + const m = a.length, n = b.length; + if (!m) return n; if (!n) return m; + const d = Array.from({ length: m + 1 }, (_, i) => [i, ...Array(n).fill(0)]); + for (let j = 0; j <= n; j++) d[0][j] = j; + for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); + return d[m][n]; +} +// Fuzzy first-name match within the (small) channel-member pool: catches transcription +// misspellings like "Claire" -> Clare Dillon. Conservative on purpose - only fires for a name +// >=5 chars that is within edit distance 1 of exactly one channel member, so it can't grab a +// common word or pick the wrong person. +function fuzzyFirstId(tok) { + const t = canon(tok); + if (t.length < 5) return null; + let hit = null; + for (const [c, set] of Object.entries(byFirstC)) { + if (c.length < 5 || set.size !== 1) continue; + if (lev(t, c) <= 1) { const id = [...set][0]; if (hit && hit !== id) return null; hit = id; } + } + return hit; +} +// Resolve an action-item owner token (may be dotted/underscored, e.g. "Micaela.Eller"). +function resolveId(name) { + const raw = (name || '').trim(); + for (const v of [raw, raw.replace(/[._]+/g, ' ')]) { const id = byName[norm(v)]; if (id) return id; } + const set = byFirstC[canon(raw.split(/[.\s_]+/)[0])]; + if (set && set.size === 1) return [...set][0]; + return fuzzyFirstId(raw.split(/[.\s_]+/)[0]); +} +// Tag any channel member named anywhere in free text (full names, then unique first names, +// then a tight fuzzy pass over remaining capitalized words for misspelled names). +function resolveProse(text) { + let out = text || ''; + for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) { + out = out.replace(new RegExp('\\b' + esc(name) + '\\b', 'gi'), '<@' + byName[name] + '>'); + } + for (const [c, set] of Object.entries(byFirstC)) { + if (set.size !== 1) continue; + const id = [...set][0]; + for (const t of [c, ...(aliasVariants[c] || [])]) out = out.replace(new RegExp('\\b' + esc(t) + '\\b', 'gi'), '<@' + id + '>'); + } + out = out.replace(/\b[A-Z][a-z]{4,}\b/g, (w) => { const id = fuzzyFirstId(w); return id ? '<@' + id + '>' : w; }); + return out; +} +// Chatham House series: never tag or name a participant. Any channel member's name that survived the +// anonymizing filter is replaced with a neutral stand-in (a backstop - the filter already strips names). +function scrub(text) { + let out = text || ''; + const anon = (m, poss, at, str) => (/(^|[.!?:*\n]\s*)$/.test(str.slice(0, at)) ? 'A' : 'a') + ' participant' + (poss || ''); + for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) { + out = out.replace(new RegExp('\\b' + esc(name) + '(\'s)?\\b', 'gi'), anon); + } + for (const c of Object.keys(byFirstC)) { + for (const t of [c, ...(aliasVariants[c] || [])]) { + out = out.replace(new RegExp('\\b' + esc(t[0].toUpperCase() + t.slice(1)) + '(\'s)?\\b', 'g'), anon); + } + } + return out; +} +const CH = !!rec.chathamHouse; +// A leading 'Name:' / 'First Last:' owner prefix, dropped on a Chatham House series. +const OWNER_PREFIX = /^[A-Z][\w.'-]*(?: [A-Z][\w.'-]*){0,2}$/; +// Action items: resolve the owner token, then tag any members named in the rest of the line. +// Chatham House series: group next steps by owner under anonymous labels (Person 1, Person 2, ...) +// numbered by first appearance, so attendees can still tell which tasks belong together. +let chStepsText = ''; +if (CH) { + const people = new Map(); + const loose = []; + for (const line of (rec.nextSteps || [])) { + const s = String(line); + const j = s.indexOf(':'); + const nm = j > -1 ? s.slice(0, j).trim() : ''; + if (nm && OWNER_PREFIX.test(nm)) { + const key = resolveId(nm) || canon(nm.split(/[.\s_]+/)[0]); + if (!people.has(key)) people.set(key, []); + people.get(key).push(scrub(s.slice(j + 1).trim())); + } else { + loose.push(scrub(s.trim())); + } + } + const parts = []; + let n = 0; + for (const tasks of people.values()) parts.push('*Person ' + (++n) + '*\n' + tasks.map(t => '• ' + t).join('\n')); + if (loose.length) parts.push((n ? '*Unassigned*\n' : '') + loose.map(t => '• ' + t).join('\n')); + if (parts.length) chStepsText = '*Next steps*\n' + parts.join('\n\n'); +} +const steps = CH ? [] : (rec.nextSteps || []).map(line => { + const s = String(line); + const i = s.indexOf(':'); + if (i === -1) return '• ' + resolveProse(s.trim()); + const nm = s.slice(0, i); + const id = resolveId(nm); + const owner = id ? '<@' + id + '>' : '*' + nm.trim() + '*'; + return '• ' + owner + ': ' + resolveProse(s.slice(i + 1).trim()); +}); +function sectionBlocks(text) { + const out = []; let cur = ''; + for (const line of (text || '').split('\n')) { + if ((cur + '\n' + line).length > 2900) { if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } }); cur = line; } + else { cur = cur ? cur + '\n' + line : line; } + } + if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } }); + return out; +} +const topic = rec.topic || 'Zoom meeting'; +// The meeting's start time, formatted in UTC (neutral for the global InnerSource community). +function fmtUTC(iso) { + const d = new Date(iso); + if (isNaN(d.getTime())) return ''; + const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + let h = d.getUTCHours(); + const ampm = h >= 12 ? 'PM' : 'AM'; + h = h % 12 || 12; + return months[d.getUTCMonth()] + ' ' + d.getUTCDate() + ', ' + d.getUTCFullYear() + ', ' + h + ':' + String(d.getUTCMinutes()).padStart(2, '0') + ' ' + ampm + ' UTC'; +} +const when = fmtUTC(rec.meetingStart); +const title = 'Meeting recap - ' + topic + (when ? ' (' + when + ')' : ''); +const recap = CH ? scrub(rec.recap || '') : resolveProse(rec.recap || ''); +const blocks = [{ type: 'section', text: { type: 'mrkdwn', text: '*:memo: ' + title + '*' } }]; +if (recap) blocks.push(...sectionBlocks(recap)); +if (steps.length) { blocks.push({ type: 'divider' }); blocks.push(...sectionBlocks('*Next steps*\n' + steps.join('\n'))); } +if (chStepsText) { blocks.push({ type: 'divider' }); blocks.push(...sectionBlocks(chStepsText)); } +if (CH) blocks.push({ type: 'context', elements: [{ type: 'mrkdwn', text: ':lock: Held under the Chatham House Rule - names and affiliations are left out of these notes, and action-item owners are shown as Person 1, Person 2, and so on.' }] }); +return [{ json: { channel: rec.channel, meetingUuid: rec.meetingUuid, blocks: blocks.slice(0, 48), fallbackText: title } }]; + diff --git a/src/zoom-recaps-to-slack/gate.js b/src/zoom-recaps-to-slack/gate.js new file mode 100644 index 0000000..df64ee6 --- /dev/null +++ b/src/zoom-recaps-to-slack/gate.js @@ -0,0 +1,23 @@ +// Content + cooldown gate. Drop un-generated shells and summaries still being refined. +const s = $json || {}; +const cand = $('Attach Fields').item.json; +const COOLDOWN_MIN = 15; +const hasContent = !!(s.summary_overview || (Array.isArray(s.next_steps) && s.next_steps.length)); +if (!hasContent) return []; +const modIso = s.summary_last_modified_time || s.summary_created_time; +if (modIso) { + const ageMin = (Date.now() - new Date(modIso).getTime()) / 60000; + if (ageMin < COOLDOWN_MIN) return []; +} +return [{ json: { + meetingUuid: cand.meetingUuid, + meetingId: cand.meetingId, + channel: cand.channel, + chathamHouse: !!cand.chathamHouse, + topic: s.meeting_topic || cand.topic, + meetingStart: s.meeting_start_time || cand.meetingStart, + recap: s.summary_overview || '', + nextSteps: Array.isArray(s.next_steps) ? s.next_steps : [], + summaryDetails: Array.isArray(s.summary_details) ? s.summary_details : [], + docUrl: s.summary_doc_url || '', +}}]; diff --git a/src/zoom-recaps-to-slack/read-raw-body.js b/src/zoom-recaps-to-slack/read-raw-body.js new file mode 100644 index 0000000..fd40902 --- /dev/null +++ b/src/zoom-recaps-to-slack/read-raw-body.js @@ -0,0 +1,5 @@ +// Zoom signs the exact bytes it sent, so keep the raw request body alongside the parsed one. +// (The Webhook node's Raw Body option stores those bytes as the binary property "data".) +const raw = (await this.helpers.getBinaryDataBuffer(0, 'data')).toString('utf8'); +return [{ json: { headers: $json.headers || {}, body: $json.body || {}, raw } }]; + diff --git a/src/zoom-recaps-to-slack/reset-a.js b/src/zoom-recaps-to-slack/reset-a.js new file mode 100644 index 0000000..7dca0a3 --- /dev/null +++ b/src/zoom-recaps-to-slack/reset-a.js @@ -0,0 +1 @@ +return [{ json: {} }]; diff --git a/src/zoom-recaps-to-slack/reset-b.js b/src/zoom-recaps-to-slack/reset-b.js new file mode 100644 index 0000000..7dca0a3 --- /dev/null +++ b/src/zoom-recaps-to-slack/reset-b.js @@ -0,0 +1 @@ +return [{ json: {} }]; diff --git a/src/zoom-recaps-to-slack/verify-zoom.js b/src/zoom-recaps-to-slack/verify-zoom.js new file mode 100644 index 0000000..c314d4a --- /dev/null +++ b/src/zoom-recaps-to-slack/verify-zoom.js @@ -0,0 +1,34 @@ +// Decide how to answer Zoom, and whether this call should go on to post a recap. +// - endpoint.url_validation: prove we hold the app's secret token by returning the HMAC of plainToken. +// - anything else must carry a valid x-zm-signature (HMAC of "v0::"), so only +// Zoom can trigger a post; a bad or missing signature gets a 401 and stops here. +// - only meeting.summary_completed goes on to the posting path. +// Zoom wants the answer within 3 seconds, so this node only decides; the slow work runs after the reply. +const crypto = require('crypto'); +const req = $('Read Raw Body').first().json; +const secret = String(($('Webhook Secret').first().json || {}).secretToken || '').trim(); +const hmac = (msg) => crypto.createHmac('sha256', secret).update(msg).digest('hex'); +const body = req.body || {}; +const event = body.event || ''; + +if (!secret) return [{ json: { status: 500, response: { error: 'webhook secret not configured' }, proceed: false } }]; + +if (event === 'endpoint.url_validation') { + const plainToken = String((body.payload || {}).plainToken || ''); + return [{ json: { status: 200, response: { plainToken, encryptedToken: hmac(plainToken) }, proceed: false } }]; +} + +const sent = String(req.headers['x-zm-signature'] || ''); +const expected = 'v0=' + hmac('v0:' + (req.headers['x-zm-request-timestamp'] || '') + ':' + req.raw); +const valid = sent.length === expected.length && crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(expected)); +if (!valid) return [{ json: { status: 401, response: { error: 'invalid signature' }, proceed: false } }]; + +const obj = (body.payload || {}).object || {}; +return [{ json: { + status: 200, + response: { ok: true }, + proceed: event === 'meeting.summary_completed', + meetingId: String(obj.meeting_id || obj.id || ''), + meetingUuid: obj.meeting_uuid || obj.uuid || '', +} }]; + From 3209e29605cbcdef014c40d7730d00e6abe11ff9 Mon Sep 17 00:00:00 2001 From: Russ Rutledge Date: Tue, 27 Oct 2026 16:43:03 -0500 Subject: [PATCH 2/3] Keep Code-node code only in src/; publishing fills it into the workflow Each Code node's jsCode in the committed workflow JSON is now a one-line comment naming its src/ file, so a code change touches only the .js file. update-workflow.sh fills the code in before uploading, a merge that changes only src/ publishes the workflows it touches, make build writes filled-in workflows to dist/, and the CI check fails when a Code node holds code or names a missing file, or a src/ file is unused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AEavKGR3wFFUQXR9W16mSQ --- .github/workflows/check-code-nodes.yml | 6 +- .github/workflows/publish-n8n.yml | 4 +- .gitignore | 3 + Makefile | 6 +- USAGE.md | 30 ++-- nodes/New Member Introduction.json | 2 +- nodes/Send Bulk DM.json | 6 +- nodes/ZOOM_RECAPS_TO_SLACK.md | 4 +- nodes/Zoom Recaps to Slack.json | 22 +-- nodes/governance/ISC - GDrive.json | 10 +- ...Summit \342\200\224 Keynote Reachout.json" | 6 +- nodes/working-group-roles/ISC - Crier.json | 2 +- scripts/code-nodes.js | 165 ++++++++++++------ scripts/update-workflow.sh | 11 +- 14 files changed, 170 insertions(+), 107 deletions(-) diff --git a/.github/workflows/check-code-nodes.yml b/.github/workflows/check-code-nodes.yml index 0110aaa..30de8c8 100644 --- a/.github/workflows/check-code-nodes.yml +++ b/.github/workflows/check-code-nodes.yml @@ -1,4 +1,4 @@ -name: Check Code-node source matches workflow JSON +name: Check Code nodes point at src/ on: pull_request: @@ -14,9 +14,5 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 20 - - name: Check run: node scripts/code-nodes.js check diff --git a/.github/workflows/publish-n8n.yml b/.github/workflows/publish-n8n.yml index 6e84e9d..2314df5 100644 --- a/.github/workflows/publish-n8n.yml +++ b/.github/workflows/publish-n8n.yml @@ -5,6 +5,7 @@ on: branches: [main] paths: - "nodes/**/*.json" + - "src/**/*.js" workflow_dispatch: inputs: file: @@ -37,7 +38,8 @@ jobs: set -euo pipefail git config core.quotepath off if [ "${{ github.event_name }}" == "push" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then - git diff -z --name-only --diff-filter=AM "$BEFORE_SHA" "$AFTER_SHA" -- 'nodes/*.json' > "$RUNNER_TEMP/files.list" + git diff -z --name-only --diff-filter=AM "$BEFORE_SHA" "$AFTER_SHA" -- 'nodes/*.json' 'src/*.js' \ + | node scripts/code-nodes.js affected > "$RUNNER_TEMP/files.list" elif [ -n "$INPUT_FILE" ]; then printf '%s\0' "$INPUT_FILE" > "$RUNNER_TEMP/files.list" else diff --git a/.gitignore b/.gitignore index d4fc4ad..27bbd15 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,9 @@ Thumbs.db # Docker volumes and data n8n_data/ +# Workflows built with their Code-node code filled in (make build) +dist/ + # Temporary files *.tmp *.log diff --git a/Makefile b/Makefile index 33b238a..e6ed161 100644 --- a/Makefile +++ b/Makefile @@ -3,17 +3,17 @@ validate-json: find nodes -name '*.json' -exec python3 -c 'import json,sys; f=sys.argv[1]; json.load(open(f)); print("Valid:", f)' {} \; -# Write the Code-node JavaScript in src/ into the workflow JSON under nodes/ +# Write every workflow, with its Code-node code filled in from src/, to dist/ .PHONY: build build: node scripts/code-nodes.js build -# Fail if the workflow JSON under nodes/ differs from what build would write +# Fail unless every Code node points at a source file in src/ and every source file is used .PHONY: check check: node scripts/code-nodes.js check -# Rewrite src/ from each Code node's jsCode, removing files whose node is gone +# Move real code found in the workflow JSON into src/, leaving placeholders .PHONY: extract extract: node scripts/code-nodes.js extract diff --git a/USAGE.md b/USAGE.md index d180dca..1f1ee7b 100644 --- a/USAGE.md +++ b/USAGE.md @@ -9,30 +9,29 @@ ## Publishing workflows to n8n Cloud -Merging a change to a workflow JSON under `nodes/` into `main` publishes it to automatically, through the `Publish workflows to n8n Cloud` GitHub Action. -The Action publishes only the workflow files that changed in the push. -Each file is matched to its workflow by the `id` field in the JSON. +Merging a change to a workflow JSON under `nodes/`, or to one of its Code nodes' files under `src/`, into `main` publishes that workflow to automatically, through the `Publish workflows to n8n Cloud` GitHub Action. +The Action publishes only the workflows that changed in the push. +Each workflow JSON is matched to its n8n workflow by its `id` field. Publishing replaces the workflow's name, nodes, connections, settings, and static data, and leaves its active or inactive state as it is. The Action reads the API key from the `N8N_API_KEY` repository secret. ## Editing a Code node's JavaScript -Each Code node's JavaScript lives in its own file under `src/`, so a pull request shows a code change as ordinary lines of JavaScript. -A Code node's file is `src///.js`, with each name lowercased and every run of other characters turned into a hyphen. +Each Code node's JavaScript lives only in its own file under `src/`, so a pull request shows a code change as ordinary lines of JavaScript. +In the workflow JSON, the node's code is the one-line comment `// Code comes from src/.js at build time.`, naming that file. +Publishing fills in the real code from the file, through `scripts/update-workflow.sh`, which the GitHub Action and a manual publish both run. The code runs as the body of an n8n Code node, so a top-level `return` and n8n's built-in globals are valid there even where an editor marks them as errors. -To change a Code node: +To change a Code node, edit its file under `src/` and commit it. -1. Edit its file under `src/`. -2. Run `make build` (or `node scripts/code-nodes.js build`), which writes the code into the workflow JSON under `nodes/` and changes only the edited node's `jsCode` line. -3. Commit both the `.js` file and the workflow JSON. +`make build` writes every workflow with its code filled in to `dist/`, ready to import into an n8n instance by hand. +The `Check Code nodes point at src/` GitHub Action fails a pull request in which a Code node holds code instead of naming a file, names a file that doesn't exist, or a file under `src/` belongs to no Code node; run `make check` to see the same result locally. -The workflow JSON stays committed because it is what publishing sends to n8n Cloud. -The `Check Code-node source matches workflow JSON` GitHub Action fails a pull request whose workflow JSON differs from what `make build` writes from `src/`; run `make check` to see the same result locally. - -When a workflow comes from an export of the n8n editor, or gains, loses, or renames a Code node, run `make extract` to rewrite `src/` from the workflow JSON. -Extract writes one file per Code node, removes files whose node is gone, and stops with an error if building from those files would not reproduce the workflow JSON byte for byte. +When a workflow comes from an export of the n8n editor, its Code nodes hold their real code. +Copy the export over the workflow's file under `nodes/` and run `make extract`, which moves each node's code into `src/` and puts the one-line comment back in the JSON. +A new Code node's file is `src///.js`, with each name lowercased and every run of characters other than letters and digits turned into a hyphen. +Extract also removes files under `src/` whose Code node is gone, and stops with an error if publishing would not reproduce the exported code exactly. ## Credential errors (e.g. “does not exist for type …”) @@ -41,6 +40,7 @@ n8n stores credentials by **ID** on the server. If you see `Credential with ID " 1. Open the workflow in the editor, select that node, and under **Credential** choose an existing **Google Drive OAuth2 API** credential (or create one and connect it). 2. Save the workflow. -Workflow JSON in this repo omits credential IDs where possible so a fresh import asks you to map credentials by name instead of reusing another instance’s IDs. If your copy still has a bad ID, fix it in the UI as above, or re-import the workflow from `nodes/working-group-roles/ISC - GDrive.json` and attach your Drive credential when prompted. +Workflow JSON in this repo omits credential IDs where possible so a fresh import asks you to map credentials by name instead of reusing another instance’s IDs. +If your copy still has a bad ID, fix it in the UI as above, or run `make build` and re-import the workflow from `dist/governance/ISC - GDrive.json` and attach your Drive credential when prompted. **Google Drive + HTTP Request:** Some Google OAuth credentials are configured to **disallow** use inside the **HTTP Request** node (n8n blocks this for security). Workflows such as **ISC - GDrive** use the **Google Drive** node instead so the same APIs run without that restriction. \ No newline at end of file diff --git a/nodes/New Member Introduction.json b/nodes/New Member Introduction.json index 6aa2bee..1d4e1a9 100644 --- a/nodes/New Member Introduction.json +++ b/nodes/New Member Introduction.json @@ -131,7 +131,7 @@ }, { "parameters": { - "jsCode": "// Edit the blocks array below to match Slack Block Kit. Copy the whole blocks array\n// and paste into https://app.slack.com/block-kit-builder/ to preview.\n// block_kit_builder_url in the output opens the builder with this payload.\nconst displayName = $input.first().json.new_user_display_name || 'there';\nconst blocks = [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `*Hey ${displayName}!*\\n\\nWelcome to the InnerSource Commons! It's so cool you're here! 🎉\\n\\nThis is a global community of practitioners, researchers, and curious minds all exploring how open collaboration works inside organizations.`\n }\n },\n { type: 'divider' },\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: \"👋 *Head over to <#C0867TAF63H|newcomers> and tell us a little about yourself, or choose how you'd like to get started:*\"\n }\n },\n {\n type: 'actions',\n elements: [\n { type: 'button', text: { type: 'plain_text', text: '📖 Quick Start Guide', emoji: true }, url: 'https://innersourcecommons.org/community/quick-start-guide/' },\n { type: 'button', text: { type: 'plain_text', text: '📅 Join a Meeting', emoji: true }, url: 'https://innersourcecommons.org/community/calendar/' },\n { type: 'button', text: { type: 'plain_text', text: '🏢 Pattern Library', emoji: true }, url: 'https://patterns.innersourcecommons.org/' }\n ]\n },\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: '🌍 Join a Regional Community: <#C07MXDSG2P8|africa> <#C03M546NR16|japan>'\n }\n },\n { type: 'divider' },\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: '🔎 *Explore channels that match your interests:*\\n\\n• <#C2EFRTS6A|innersource-patterns> — practical patterns for making innersource work\\n• <#C046MD5R5RT|local-community> — find or start a gathering near you\\n• <#C04DT6NQX7G|ispo-working-group> — dive into standards and best practices'\n }\n },\n { type: 'divider' },\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: '💬 Looking for something else? Ask in <#C04PXKRN4|general>, and the community will be happy to help!'\n }\n }\n];\nconst payload = { blocks };\nconst blockKitBuilderUrl = 'https://app.slack.com/block-kit-builder/T04PXKRM0#' + encodeURIComponent(JSON.stringify(payload));\nreturn $input.all().map(item => ({\n json: {\n ...item.json,\n blocks,\n blocks_json: JSON.stringify(payload, null, 2),\n block_kit_builder_url: blockKitBuilderUrl\n }\n}));\n" + "jsCode": "// Code comes from src/new-member-introduction/slack-welcome-message-block-kit.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, diff --git a/nodes/Send Bulk DM.json b/nodes/Send Bulk DM.json index 1463b17..56ebc1e 100644 --- a/nodes/Send Bulk DM.json +++ b/nodes/Send Bulk DM.json @@ -14,7 +14,7 @@ }, { "parameters": { - "jsCode": "const staticData = $getWorkflowStaticData('global');\nstaticData.allMembers = [];\nreturn [{ json: { cursor: '' } }];" + "jsCode": "// Code comes from src/send-bulk-dm/init-pagination.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, @@ -49,7 +49,7 @@ }, { "parameters": { - "jsCode": "const staticData = $getWorkflowStaticData('global');\nconst response = $input.first().json;\nif (response.members) {\n staticData.allMembers.push(...response.members);\n}\nconst nextCursor = response.response_metadata?.next_cursor || '';\nreturn [{ json: { cursor: nextCursor } }];" + "jsCode": "// Code comes from src/send-bulk-dm/collect-members.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, @@ -94,7 +94,7 @@ }, { "parameters": { - "jsCode": "const staticData = $getWorkflowStaticData('global');\nconst allMembers = staticData.allMembers || [];\nreturn [{ json: { members: allMembers } }];" + "jsCode": "// Code comes from src/send-bulk-dm/output-all-members.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, diff --git a/nodes/ZOOM_RECAPS_TO_SLACK.md b/nodes/ZOOM_RECAPS_TO_SLACK.md index d9f09dd..287ef9c 100644 --- a/nodes/ZOOM_RECAPS_TO_SLACK.md +++ b/nodes/ZOOM_RECAPS_TO_SLACK.md @@ -59,11 +59,11 @@ The JSON carries the credential ids of the ISC instance, which a different insta ## Loading a change into n8n The workflow's n8n id is `pLIk4d8AYwAmpxpz`. -After a change to `Zoom Recaps to Slack.json` merges, load it with: +After a change to `Zoom Recaps to Slack.json` or to its code under `src/zoom-recaps-to-slack/` merges, load it with: ```bash N8N_API_KEY= ./scripts/update-workflow.sh "nodes/Zoom Recaps to Slack.json" ``` -The script sends the file to the n8n public API with a PUT. +The script fills in each Code node's code from `src/zoom-recaps-to-slack/` and sends the workflow to the n8n public API with a PUT. Check in the editor that the workflow is still active afterwards. diff --git a/nodes/Zoom Recaps to Slack.json b/nodes/Zoom Recaps to Slack.json index 54c8f9d..84867f3 100644 --- a/nodes/Zoom Recaps to Slack.json +++ b/nodes/Zoom Recaps to Slack.json @@ -32,7 +32,7 @@ -304 ], "parameters": { - "jsCode": "// Zoom signs the exact bytes it sent, so keep the raw request body alongside the parsed one.\n// (The Webhook node's Raw Body option stores those bytes as the binary property \"data\".)\nconst raw = (await this.helpers.getBinaryDataBuffer(0, 'data')).toString('utf8');\nreturn [{ json: { headers: $json.headers || {}, body: $json.body || {}, raw } }];\n" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/read-raw-body.js at build time." }, "notes": "Keeps the raw request body next to the parsed one for the signature check.", "notesInFlow": true @@ -77,7 +77,7 @@ -304 ], "parameters": { - "jsCode": "// Decide how to answer Zoom, and whether this call should go on to post a recap.\n// - endpoint.url_validation: prove we hold the app's secret token by returning the HMAC of plainToken.\n// - anything else must carry a valid x-zm-signature (HMAC of \"v0::\"), so only\n// Zoom can trigger a post; a bad or missing signature gets a 401 and stops here.\n// - only meeting.summary_completed goes on to the posting path.\n// Zoom wants the answer within 3 seconds, so this node only decides; the slow work runs after the reply.\nconst crypto = require('crypto');\nconst req = $('Read Raw Body').first().json;\nconst secret = String(($('Webhook Secret').first().json || {}).secretToken || '').trim();\nconst hmac = (msg) => crypto.createHmac('sha256', secret).update(msg).digest('hex');\nconst body = req.body || {};\nconst event = body.event || '';\n\nif (!secret) return [{ json: { status: 500, response: { error: 'webhook secret not configured' }, proceed: false } }];\n\nif (event === 'endpoint.url_validation') {\n const plainToken = String((body.payload || {}).plainToken || '');\n return [{ json: { status: 200, response: { plainToken, encryptedToken: hmac(plainToken) }, proceed: false } }];\n}\n\nconst sent = String(req.headers['x-zm-signature'] || '');\nconst expected = 'v0=' + hmac('v0:' + (req.headers['x-zm-request-timestamp'] || '') + ':' + req.raw);\nconst valid = sent.length === expected.length && crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(expected));\nif (!valid) return [{ json: { status: 401, response: { error: 'invalid signature' }, proceed: false } }];\n\nconst obj = (body.payload || {}).object || {};\nreturn [{ json: {\n status: 200,\n response: { ok: true },\n proceed: event === 'meeting.summary_completed',\n meetingId: String(obj.meeting_id || obj.id || ''),\n meetingUuid: obj.meeting_uuid || obj.uuid || '',\n} }];\n" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/verify-zoom.js at build time." }, "notes": "Answers Zoom's URL validation with the HMAC of its challenge, and requires a valid x-zm-signature on every other call (401 otherwise). Decides the reply; does not post.", "notesInFlow": true @@ -294,7 +294,7 @@ }, { "parameters": { - "jsCode": "// Pick the one meeting to post this run: the newest UNPOSTED occurrence of any configured meeting\n// (on a webhook run, of the triggering meeting only) whose summary is ready to post (see readyToPost). An occurrence with nothing to post - a room started\n// and stopped in seconds, a summary Zoom never generated, a failed fetch - is skipped, never allowed to\n// block the occurrences behind it. Calendar guardrail: a meeting headed for a PUBLIC channel\n// must match a scheduled public-calendar event (same Zoom meeting id + weekday/time) - this stops a\n// different meeting that borrowed the same Zoom room (e.g. a board meeting) from posting to a public\n// channel. Meetings headed for PRIVATE channels post without that check. Emits 0 or 1 item.\nconst token = $('Get Zoom Token').first().json.access_token;\n\nconst config = {};\nconst chatham = {};\nfor (const r of $('All Config').all()) { const j = r.json || {}; if (j.meetingId) { config[String(j.meetingId)] = j.channel; chatham[String(j.meetingId)] = j.chathamHouse === true; } }\nconst posted = new Set($('All Posted').all().map(r => (r.json || {}).occurrenceUuid).filter(Boolean));\n\n// Channel privacy from the conversations.list side fetch; default to private (safe) if unknown.\nconst chans = $('Slack: conversations.list').all().flatMap(i => (i.json.channels) || []);\nconst isPrivateChannel = (name) => { const c = chans.find(x => '#' + x.name === name); return c ? !!c.is_private : true; };\n\n// Public-calendar iCal text (fetched upstream, no auth).\nconst j = $('Public Calendar').first().json;\nconst ical = (j && (j.data || (typeof j === 'string' ? j : j.body))) || '';\nfunction matchesPublicEvent(icalText, meetingId, occurrenceIso) {\n const text = (icalText || '').replace(/\\r?\\n[ \\t]/g, ''); // unfold continuation lines\n const events = text.split('BEGIN:VEVENT').slice(1);\n const occ = new Date(occurrenceIso);\n const occDate = occurrenceIso.slice(0, 10).replace(/-/g, '');\n const occWeekday = occ.getUTCDay();\n const occMin = occ.getUTCHours() * 60 + occ.getUTCMinutes();\n for (const e of events) {\n if (!e.includes(String(meetingId))) continue;\n const dt = (e.match(/DTSTART[^:]*:([0-9T]+Z?)/) || [])[1];\n if (!dt) continue;\n if (dt.slice(0, 8) === occDate) return true; // concrete instance on the same date\n if (/Z$/.test(dt)) { // recurring UTC slot: match weekday + time-of-day\n const h = +dt.slice(9, 11), mi = +dt.slice(11, 13);\n const evd = new Date(Date.UTC(+dt.slice(0, 4), +dt.slice(4, 6) - 1, +dt.slice(6, 8), h, mi));\n if (evd.getUTCDay() === occWeekday && Math.abs((h * 60 + mi) - occMin) <= 90) return true;\n }\n }\n return false;\n}\n\n// Flatten every summary across the paginated List Summaries responses.\nconst all = [];\nfor (const it of $('List Summaries').all()) for (const s of (((it.json || {}).summaries) || [])) all.push(s);\n\n// A webhook run handles only the meeting that triggered it, so two meetings finishing close together\n// don't race for the same run. Verify Zoom only has output on the webhook path; the daily sweep never\n// executes it, so reading it there throws and the sweep keeps considering every configured meeting.\nlet trigger = null;\ntry { trigger = $('Verify Zoom').first().json; } catch (e) { trigger = null; }\nconst triggerId = trigger && trigger.meetingId ? String(trigger.meetingId) : '';\nconst triggerUuid = trigger && trigger.meetingUuid ? String(trigger.meetingUuid) : '';\n\n// Every unposted occurrence of a configured meeting, newest first.\nlet eligible = all\n .filter(s => config[String(s.meeting_id)] && !posted.has(s.meeting_uuid))\n .filter(s => !triggerId || String(s.meeting_id) === triggerId)\n .sort((a, b) => new Date(b.meeting_start_time) - new Date(a.meeting_start_time));\n// Prefer the exact occurrence that triggered the webhook; if the list doesn't show it yet, fall back to\n// the newest unposted occurrence of the same meeting.\nif (triggerUuid && eligible.some(s => s.meeting_uuid === triggerUuid)) eligible = eligible.filter(s => s.meeting_uuid === triggerUuid);\n\n// Same test as the Gate (content present, summary not still being refined), asked here so an\n// occurrence that fails it is passed over instead of ending the run. Any fetch error counts as not ready.\nconst COOLDOWN_MIN = 15;\nconst readyToPost = async (s) => {\n try {\n const d = await this.helpers.httpRequest({\n method: 'GET',\n url: 'https://api.zoom.us/v2/meetings/' + encodeURIComponent(encodeURIComponent(s.meeting_uuid)) + '/meeting_summary',\n headers: { Authorization: 'Bearer ' + token },\n json: true,\n });\n if (!(d.summary_overview || (Array.isArray(d.next_steps) && d.next_steps.length))) return false;\n const modIso = d.summary_last_modified_time || d.summary_created_time;\n return !modIso || (Date.now() - new Date(modIso).getTime()) / 60000 >= COOLDOWN_MIN;\n } catch (e) { return false; }\n};\n\n// Pick the newest that clears the guardrail and is ready.\nlet chosen = null;\nfor (const s of eligible) {\n const channel = config[String(s.meeting_id)];\n // public channel + no matching public event -> a room-reuse; skip it, try the next.\n if (!isPrivateChannel(channel) && !matchesPublicEvent(ical, s.meeting_id, s.meeting_start_time)) continue;\n if (await readyToPost(s)) { chosen = s; break; }\n}\nif (!chosen) return [];\n\nreturn [{ json: {\n meetingUuid: chosen.meeting_uuid,\n meetingId: String(chosen.meeting_id),\n topic: chosen.meeting_topic,\n meetingStart: chosen.meeting_start_time,\n channel: config[String(chosen.meeting_id)],\n chathamHouse: !!chatham[String(chosen.meeting_id)],\n occurrenceUuid: chosen.meeting_uuid,\n token,\n}}];\n" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/build-candidates.js at build time." }, "id": "a1000000-0000-0000-0000-000000000004", "name": "Build Candidates", @@ -331,7 +331,7 @@ }, { "parameters": { - "jsCode": "// Content + cooldown gate. Drop un-generated shells and summaries still being refined.\nconst s = $json || {};\nconst cand = $('Attach Fields').item.json;\nconst COOLDOWN_MIN = 15;\nconst hasContent = !!(s.summary_overview || (Array.isArray(s.next_steps) && s.next_steps.length));\nif (!hasContent) return [];\nconst modIso = s.summary_last_modified_time || s.summary_created_time;\nif (modIso) {\n const ageMin = (Date.now() - new Date(modIso).getTime()) / 60000;\n if (ageMin < COOLDOWN_MIN) return [];\n}\nreturn [{ json: {\n meetingUuid: cand.meetingUuid,\n meetingId: cand.meetingId,\n channel: cand.channel,\n chathamHouse: !!cand.chathamHouse,\n topic: s.meeting_topic || cand.topic,\n meetingStart: s.meeting_start_time || cand.meetingStart,\n recap: s.summary_overview || '',\n nextSteps: Array.isArray(s.next_steps) ? s.next_steps : [],\n summaryDetails: Array.isArray(s.summary_details) ? s.summary_details : [],\n docUrl: s.summary_doc_url || '',\n}}];" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/gate.js at build time." }, "id": "a1000000-0000-0000-0000-000000000006", "name": "Gate", @@ -344,7 +344,7 @@ }, { "parameters": { - "jsCode": "// Config Lookup produced the channel row (or nothing => not in allowlist, drop).\nconst channel = $json.channel;\nif (!channel) return [];\nconst cand = $('Build Candidates').item.json;\nreturn [{ json: { ...cand, channel } }];" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/attach-fields.js at build time." }, "id": "a1000000-0000-0000-0000-000000000008", "name": "Attach Fields", @@ -430,7 +430,7 @@ }, { "parameters": { - "jsCode": "// Resolve names to Slack @-mentions and build the Block Kit recap.\n// Mentions are gated to ACTUAL MEMBERS of the target channel: a name is tagged only when\n// it resolves to a Slack user who belongs to the channel this recap posts to. That tags every\n// attendee who's in the channel (in prose and in action items) and leaves genuinely external\n// people plain, and it disambiguates common names for free (e.g. among 9 \"Jeff\"s in the\n// workspace, only the one in the channel gets the ping).\nconst rec = $('Skip If Already Posted').item.json;\nconst memberIds = new Set($('Slack: conversations.members').all().flatMap(i => (i.json.members) || []));\nconst members = $('Slack: users.list').all()\n .flatMap(i => (i.json.members) || [])\n .filter(m => memberIds.has(m.id) && !m.deleted && !m.is_bot && m.id !== 'USLACKBOT');\nconst norm = x => (x || '').toString().trim().toLowerCase();\n// Nickname families: a spelling on the left, when it appears in the text, resolves to a member\n// whose first name is the canonical form on the right (lets \"Russell\" reach the member \"Russ\").\nconst ALIAS = { russell: 'russ' };\nconst canon = f => ALIAS[norm(f)] || norm(f);\nconst aliasVariants = {}; // canonical -> extra text spellings that should also match\nfor (const [variant, c] of Object.entries(ALIAS)) (aliasVariants[c] = aliasVariants[c] || []).push(variant);\n// Common words that show up in recap prose but are also, occasionally, someone's junk Slack name\n// (e.g. a user whose real name is literally \"name\"). Never treat these as a first name to tag.\nconst COMMON_WORDS = new Set(['name', 'names', 'team', 'teams', 'board', 'group', 'groups', 'call', 'calls', 'meeting', 'meetings', 'note', 'notes', 'update', 'updates', 'staff', 'work', 'works', 'next', 'step', 'steps', 'item', 'items', 'all', 'new', 'lead', 'leads', 'chair', 'member', 'members', 'working', 'community', 'summit', 'project', 'projects', 'plan', 'plans', 'goal', 'goals', 'review', 'agenda', 'action', 'actions', 'report', 'reports', 'week', 'weeks', 'day', 'days', 'time', 'times', 'page', 'pages', 'doc', 'docs', 'content', 'video', 'videos', 'deck', 'issue', 'issues', 'code', 'user', 'users', 'test', 'admin', 'guest', 'welcome', 'thanks', 'hello']);\nconst byName = {}; // full \"first last\" -> id (channel members only)\nconst byFirstC = {}; // canonical first name -> Set (channel members only)\nfor (const m of members) {\n const p = m.profile || {};\n for (const n of [p.real_name, p.display_name, m.real_name, m.name, p.real_name_normalized, p.display_name_normalized]) {\n const k = norm(n);\n if (k && k.includes(' ') && !(k in byName)) byName[k] = m.id;\n }\n for (const n of [p.real_name, m.real_name, p.display_name, m.name]) {\n const c = canon((n || '').split(/[.\\s_]+/)[0]);\n if (c && c.length >= 3 && !COMMON_WORDS.has(c)) (byFirstC[c] = byFirstC[c] || new Set()).add(m.id);\n }\n}\nconst esc = s => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n// Levenshtein distance, used for a tight fuzzy match against the channel roster.\nfunction lev(a, b) {\n const m = a.length, n = b.length;\n if (!m) return n; if (!n) return m;\n const d = Array.from({ length: m + 1 }, (_, i) => [i, ...Array(n).fill(0)]);\n for (let j = 0; j <= n; j++) d[0][j] = j;\n for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++)\n d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));\n return d[m][n];\n}\n// Fuzzy first-name match within the (small) channel-member pool: catches transcription\n// misspellings like \"Claire\" -> Clare Dillon. Conservative on purpose - only fires for a name\n// >=5 chars that is within edit distance 1 of exactly one channel member, so it can't grab a\n// common word or pick the wrong person.\nfunction fuzzyFirstId(tok) {\n const t = canon(tok);\n if (t.length < 5) return null;\n let hit = null;\n for (const [c, set] of Object.entries(byFirstC)) {\n if (c.length < 5 || set.size !== 1) continue;\n if (lev(t, c) <= 1) { const id = [...set][0]; if (hit && hit !== id) return null; hit = id; }\n }\n return hit;\n}\n// Resolve an action-item owner token (may be dotted/underscored, e.g. \"Micaela.Eller\").\nfunction resolveId(name) {\n const raw = (name || '').trim();\n for (const v of [raw, raw.replace(/[._]+/g, ' ')]) { const id = byName[norm(v)]; if (id) return id; }\n const set = byFirstC[canon(raw.split(/[.\\s_]+/)[0])];\n if (set && set.size === 1) return [...set][0];\n return fuzzyFirstId(raw.split(/[.\\s_]+/)[0]);\n}\n// Tag any channel member named anywhere in free text (full names, then unique first names,\n// then a tight fuzzy pass over remaining capitalized words for misspelled names).\nfunction resolveProse(text) {\n let out = text || '';\n for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) {\n out = out.replace(new RegExp('\\\\b' + esc(name) + '\\\\b', 'gi'), '<@' + byName[name] + '>');\n }\n for (const [c, set] of Object.entries(byFirstC)) {\n if (set.size !== 1) continue;\n const id = [...set][0];\n for (const t of [c, ...(aliasVariants[c] || [])]) out = out.replace(new RegExp('\\\\b' + esc(t) + '\\\\b', 'gi'), '<@' + id + '>');\n }\n out = out.replace(/\\b[A-Z][a-z]{4,}\\b/g, (w) => { const id = fuzzyFirstId(w); return id ? '<@' + id + '>' : w; });\n return out;\n}\n// Chatham House series: never tag or name a participant. Any channel member's name that survived the\n// anonymizing filter is replaced with a neutral stand-in (a backstop - the filter already strips names).\nfunction scrub(text) {\n let out = text || '';\n const anon = (m, poss, at, str) => (/(^|[.!?:*\\n]\\s*)$/.test(str.slice(0, at)) ? 'A' : 'a') + ' participant' + (poss || '');\n for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) {\n out = out.replace(new RegExp('\\\\b' + esc(name) + '(\\'s)?\\\\b', 'gi'), anon);\n }\n for (const c of Object.keys(byFirstC)) {\n for (const t of [c, ...(aliasVariants[c] || [])]) {\n out = out.replace(new RegExp('\\\\b' + esc(t[0].toUpperCase() + t.slice(1)) + '(\\'s)?\\\\b', 'g'), anon);\n }\n }\n return out;\n}\nconst CH = !!rec.chathamHouse;\n// A leading 'Name:' / 'First Last:' owner prefix, dropped on a Chatham House series.\nconst OWNER_PREFIX = /^[A-Z][\\w.'-]*(?: [A-Z][\\w.'-]*){0,2}$/;\n// Action items: resolve the owner token, then tag any members named in the rest of the line.\n// Chatham House series: group next steps by owner under anonymous labels (Person 1, Person 2, ...)\n// numbered by first appearance, so attendees can still tell which tasks belong together.\nlet chStepsText = '';\nif (CH) {\n const people = new Map();\n const loose = [];\n for (const line of (rec.nextSteps || [])) {\n const s = String(line);\n const j = s.indexOf(':');\n const nm = j > -1 ? s.slice(0, j).trim() : '';\n if (nm && OWNER_PREFIX.test(nm)) {\n const key = resolveId(nm) || canon(nm.split(/[.\\s_]+/)[0]);\n if (!people.has(key)) people.set(key, []);\n people.get(key).push(scrub(s.slice(j + 1).trim()));\n } else {\n loose.push(scrub(s.trim()));\n }\n }\n const parts = [];\n let n = 0;\n for (const tasks of people.values()) parts.push('*Person ' + (++n) + '*\\n' + tasks.map(t => '• ' + t).join('\\n'));\n if (loose.length) parts.push((n ? '*Unassigned*\\n' : '') + loose.map(t => '• ' + t).join('\\n'));\n if (parts.length) chStepsText = '*Next steps*\\n' + parts.join('\\n\\n');\n}\nconst steps = CH ? [] : (rec.nextSteps || []).map(line => {\n const s = String(line);\n const i = s.indexOf(':');\n if (i === -1) return '• ' + resolveProse(s.trim());\n const nm = s.slice(0, i);\n const id = resolveId(nm);\n const owner = id ? '<@' + id + '>' : '*' + nm.trim() + '*';\n return '• ' + owner + ': ' + resolveProse(s.slice(i + 1).trim());\n});\nfunction sectionBlocks(text) {\n const out = []; let cur = '';\n for (const line of (text || '').split('\\n')) {\n if ((cur + '\\n' + line).length > 2900) { if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } }); cur = line; }\n else { cur = cur ? cur + '\\n' + line : line; }\n }\n if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } });\n return out;\n}\nconst topic = rec.topic || 'Zoom meeting';\n// The meeting's start time, formatted in UTC (neutral for the global InnerSource community).\nfunction fmtUTC(iso) {\n const d = new Date(iso);\n if (isNaN(d.getTime())) return '';\n const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n let h = d.getUTCHours();\n const ampm = h >= 12 ? 'PM' : 'AM';\n h = h % 12 || 12;\n return months[d.getUTCMonth()] + ' ' + d.getUTCDate() + ', ' + d.getUTCFullYear() + ', ' + h + ':' + String(d.getUTCMinutes()).padStart(2, '0') + ' ' + ampm + ' UTC';\n}\nconst when = fmtUTC(rec.meetingStart);\nconst title = 'Meeting recap - ' + topic + (when ? ' (' + when + ')' : '');\nconst recap = CH ? scrub(rec.recap || '') : resolveProse(rec.recap || '');\nconst blocks = [{ type: 'section', text: { type: 'mrkdwn', text: '*:memo: ' + title + '*' } }];\nif (recap) blocks.push(...sectionBlocks(recap));\nif (steps.length) { blocks.push({ type: 'divider' }); blocks.push(...sectionBlocks('*Next steps*\\n' + steps.join('\\n'))); }\nif (chStepsText) { blocks.push({ type: 'divider' }); blocks.push(...sectionBlocks(chStepsText)); }\nif (CH) blocks.push({ type: 'context', elements: [{ type: 'mrkdwn', text: ':lock: Held under the Chatham House Rule - names and affiliations are left out of these notes, and action-item owners are shown as Person 1, Person 2, and so on.' }] });\nreturn [{ json: { channel: rec.channel, meetingUuid: rec.meetingUuid, blocks: blocks.slice(0, 48), fallbackText: title } }];\n" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/format-message.js at build time." }, "id": "a1000000-0000-0000-0000-000000000011", "name": "Format Message", @@ -562,7 +562,7 @@ }, { "parameters": { - "jsCode": "// Replace recap + nextSteps with the InnerSource-Commons-only cleaned versions from the filter.\n// Privacy-safe: if the filter didn't return a usable result, SKIP posting rather than falling back\n// to the raw (unfiltered) summary. And if nothing ISC-related survived, there is nothing to post.\nconst resp = $json || {};\nconst rec = $('Gate').item.json;\nlet recap = null, nextSteps = null;\ntry {\n const text = (resp.content || []).filter(b => b.type === 'text').map(b => b.text).join('');\n const m = text.match(/\\{[\\s\\S]*\\}/);\n if (m) {\n const parsed = JSON.parse(m[0]);\n if (typeof parsed.recap === 'string') recap = parsed.recap;\n if (Array.isArray(parsed.nextSteps)) nextSteps = parsed.nextSteps;\n }\n} catch (e) {}\nif (recap === null || nextSteps === null) return [];\nrecap = recap.trim();\nif (!recap && nextSteps.length === 0) return [];\nreturn [{ json: { ...rec, recap, nextSteps } }];\n" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/apply-filter.js at build time." }, "id": "a1000000-0000-0000-0000-0000000000f2", "name": "Apply Filter", @@ -575,7 +575,7 @@ }, { "parameters": { - "jsCode": "// Build the raw full-notes text from Zoom's detailed sections, plus the main post's thread ts.\nconst rec = $('Apply Filter').item.json;\nconst details = rec.summaryDetails || [];\nconst channel = $('Format Message').item.json.channel;\nconst post = $('Slack: chat.postMessage').item.json;\nconst ts = post && post.ts;\nif (!details.length || !ts) return [];\nconst notesText = details\n .map(d => '*' + (d.label || '').toString().trim() + '*\\n' + (d.summary || '').toString().trim())\n .join('\\n\\n');\nreturn [{ json: { channel, threadTs: ts, notesText, chathamHouse: !!rec.chathamHouse } }];\n" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/format-full-notes.js at build time." }, "id": "a1000000-0000-0000-0000-0000000000n1", "name": "Format Full Notes", @@ -624,7 +624,7 @@ }, { "parameters": { - "jsCode": "// Take Claude's cleaned full-notes text, resolve member names to @-mentions, chunk into Block Kit.\n// Mentions are gated to actual members of the target channel (same rule as the main recap):\n// only a name resolving to a channel member is tagged; external names stay plain.\nconst resp = $json || {};\nconst src = $('Format Full Notes').item.json;\n// Privacy-safe: use only the filter's InnerSource-Commons-only output. If it returned nothing usable\n// (filter failed, or nothing ISC-related remained), skip the thread rather than posting raw notes.\nlet notes = null;\ntry {\n const t = (resp.content || []).filter(b => b.type === 'text').map(b => b.text).join('');\n notes = t.trim();\n} catch (e) { notes = null; }\nif (!notes) return [];\nconst memberIds = new Set($('Slack: conversations.members').all().flatMap(i => (i.json.members) || []));\nconst members = $('Slack: users.list').all()\n .flatMap(i => (i.json.members) || [])\n .filter(m => memberIds.has(m.id) && !m.deleted && !m.is_bot && m.id !== 'USLACKBOT');\nconst norm = x => (x || '').toString().trim().toLowerCase();\nconst ALIAS = { russell: 'russ' };\nconst canon = f => ALIAS[norm(f)] || norm(f);\nconst aliasVariants = {};\nfor (const [variant, c] of Object.entries(ALIAS)) (aliasVariants[c] = aliasVariants[c] || []).push(variant);\n// Common words that show up in notes prose but are also, occasionally, someone's junk Slack name.\nconst COMMON_WORDS = new Set(['name', 'names', 'team', 'teams', 'board', 'group', 'groups', 'call', 'calls', 'meeting', 'meetings', 'note', 'notes', 'update', 'updates', 'staff', 'work', 'works', 'next', 'step', 'steps', 'item', 'items', 'all', 'new', 'lead', 'leads', 'chair', 'member', 'members', 'working', 'community', 'summit', 'project', 'projects', 'plan', 'plans', 'goal', 'goals', 'review', 'agenda', 'action', 'actions', 'report', 'reports', 'week', 'weeks', 'day', 'days', 'time', 'times', 'page', 'pages', 'doc', 'docs', 'content', 'video', 'videos', 'deck', 'issue', 'issues', 'code', 'user', 'users', 'test', 'admin', 'guest', 'welcome', 'thanks', 'hello']);\nconst byName = {}, byFirstC = {};\nfor (const m of members) {\n const p = m.profile || {};\n for (const n of [p.real_name, p.display_name, m.real_name, m.name, p.real_name_normalized, p.display_name_normalized]) {\n const k = norm(n);\n if (k && k.includes(' ') && !(k in byName)) byName[k] = m.id;\n }\n for (const n of [p.real_name, m.real_name, p.display_name, m.name]) {\n const c = canon((n || '').split(/[.\\s_]+/)[0]);\n if (c && c.length >= 3 && !COMMON_WORDS.has(c)) (byFirstC[c] = byFirstC[c] || new Set()).add(m.id);\n }\n}\nconst esc = s => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\nfunction lev(a, b) {\n const m = a.length, n = b.length;\n if (!m) return n; if (!n) return m;\n const d = Array.from({ length: m + 1 }, (_, i) => [i, ...Array(n).fill(0)]);\n for (let j = 0; j <= n; j++) d[0][j] = j;\n for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++)\n d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));\n return d[m][n];\n}\nfunction fuzzyFirstId(tok) {\n const t = canon(tok);\n if (t.length < 5) return null;\n let hit = null;\n for (const [c, set] of Object.entries(byFirstC)) {\n if (c.length < 5 || set.size !== 1) continue;\n if (lev(t, c) <= 1) { const id = [...set][0]; if (hit && hit !== id) return null; hit = id; }\n }\n return hit;\n}\nfunction resolveProse(text) {\n let out = text || '';\n for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) {\n out = out.replace(new RegExp('\\\\b' + esc(name) + '\\\\b', 'gi'), '<@' + byName[name] + '>');\n }\n for (const [c, set] of Object.entries(byFirstC)) {\n if (set.size !== 1) continue;\n const id = [...set][0];\n for (const t of [c, ...(aliasVariants[c] || [])]) out = out.replace(new RegExp('\\\\b' + esc(t) + '\\\\b', 'gi'), '<@' + id + '>');\n }\n out = out.replace(/\\b[A-Z][a-z]{4,}\\b/g, (w) => { const id = fuzzyFirstId(w); return id ? '<@' + id + '>' : w; });\n return out;\n}\n// Chatham House series: never tag or name a participant. Any channel member's name that survived the\n// anonymizing filter is replaced with a neutral stand-in (a backstop - the filter already strips names).\nfunction scrub(text) {\n let out = text || '';\n const anon = (m, poss, at, str) => (/(^|[.!?:*\\n]\\s*)$/.test(str.slice(0, at)) ? 'A' : 'a') + ' participant' + (poss || '');\n for (const name of Object.keys(byName).sort((a, b) => b.length - a.length)) {\n out = out.replace(new RegExp('\\\\b' + esc(name) + '(\\'s)?\\\\b', 'gi'), anon);\n }\n for (const c of Object.keys(byFirstC)) {\n for (const t of [c, ...(aliasVariants[c] || [])]) {\n out = out.replace(new RegExp('\\\\b' + esc(t[0].toUpperCase() + t.slice(1)) + '(\\'s)?\\\\b', 'g'), anon);\n }\n }\n return out;\n}\nfunction sectionBlocks(text) {\n const out = []; let cur = '';\n for (const line of (text || '').split('\\n')) {\n if ((cur + '\\n' + line).length > 2900) { if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } }); cur = line; }\n else { cur = cur ? cur + '\\n' + line : line; }\n }\n if (cur) out.push({ type: 'section', text: { type: 'mrkdwn', text: cur } });\n return out;\n}\nnotes = src.chathamHouse ? scrub(notes) : resolveProse(notes);\nconst blocks = [{ type: 'section', text: { type: 'mrkdwn', text: '*Full notes*' } }].concat(sectionBlocks(notes)).slice(0, 48);\nreturn [{ json: { channel: src.channel, threadTs: src.threadTs, blocks } }];\n" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/apply-full-notes.js at build time." }, "id": "a1000000-0000-0000-0000-0000000000n3", "name": "Apply Full Notes", @@ -825,7 +825,7 @@ }, { "parameters": { - "jsCode": "return [{ json: {} }];" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/reset-a.js at build time." }, "id": "9d498c5f-977f-4b81-918c-822088c0d11a", "name": "Reset A", @@ -838,7 +838,7 @@ }, { "parameters": { - "jsCode": "return [{ json: {} }];" + "jsCode": "// Code comes from src/zoom-recaps-to-slack/reset-b.js at build time." }, "id": "0b934558-b201-4ad1-8df7-cfb959224cff", "name": "Reset B", diff --git a/nodes/governance/ISC - GDrive.json b/nodes/governance/ISC - GDrive.json index 03fee16..bd8f277 100644 --- a/nodes/governance/ISC - GDrive.json +++ b/nodes/governance/ISC - GDrive.json @@ -74,7 +74,7 @@ }, { "parameters": { - "jsCode": "// Build hierarchical structure from flat list of folders\n// Convert Google Drive folder structure to JSON matching the desired structure format\n\nconst rootFolderId = $('Set Configuration').first().json.rootFolderId;\n// HTTP Request shape: { files: [...] }. Google Drive Search: one item per folder.\nconst allFolders = Array.isArray($json.files)\n ? $json.files\n : $input.all().map((item) => item.json);\n\nconsole.log('Total folders found in Google Drive:', allFolders.length);\n\n// Build a map: parentId -> [children]\nconst childrenMap = new Map();\nfor (const folder of allFolders) {\n const parentId = folder.parents && folder.parents.length > 0 ? folder.parents[0] : rootFolderId;\n if (!childrenMap.has(parentId)) {\n childrenMap.set(parentId, []);\n }\n childrenMap.get(parentId).push({\n id: folder.id,\n name: folder.name\n });\n}\n\nconsole.log('Folders directly under root:', childrenMap.get(rootFolderId)?.length || 0);\n\n// Build tree structure starting directly from rootFolderId\n// Function to recursively build tree structure\nfunction buildTree(parentId) {\n const children = childrenMap.get(parentId) || [];\n return children.map(child => {\n const node = { name: child.name };\n const childChildren = buildTree(child.id);\n if (childChildren.length > 0) {\n node.children = childChildren;\n }\n return node;\n });\n}\n\n// Build tree starting from rootFolderId (which is now a folder, not a drive root)\nconst actualStructure = buildTree(rootFolderId);\n\nconsole.log('Actual structure built:', JSON.stringify(actualStructure, null, 2));\n\nreturn [{ json: { actualStructure, allFolders } }];" + "jsCode": "// Code comes from src/governance/isc-gdrive/build-actual-structure.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, @@ -88,7 +88,7 @@ }, { "parameters": { - "jsCode": "// Compare desired structure with actual structure\n// Include ALL folders with exists: true/false field\n\n// Decode HTML entities that n8n expression rendering may introduce\nfunction decodeHtmlEntities(str) {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\");\n}\n\n// Recursively decode HTML entities in all name fields\nfunction decodeNames(nodes) {\n return nodes.map(node => {\n const decoded = { ...node, name: decodeHtmlEntities(node.name) };\n if (decoded.children && decoded.children.length > 0) {\n decoded.children = decodeNames(decoded.children);\n }\n return decoded;\n });\n}\n\nconst rawDesired = typeof $('Set Configuration').first().json.desiredStructure === 'string'\n ? JSON.parse($('Set Configuration').first().json.desiredStructure)\n : $('Set Configuration').first().json.desiredStructure;\n\nconst desiredStructure = decodeNames(rawDesired);\n\nconst actualStructure = $json.actualStructure || [];\n\nconsole.log('Desired structure:', JSON.stringify(desiredStructure, null, 2));\nconsole.log('Actual structure:', JSON.stringify(actualStructure, null, 2));\n\n// Build a lookup map: parentName -> Map\n// This allows us to check if a folder exists by its name and parent context\nfunction buildNameMap(structure, parentName = null) {\n const nameMap = new Map(); // parentName -> Set\n \n function processNode(node, parent) {\n const parentKey = parent || 'ROOT';\n if (!nameMap.has(parentKey)) {\n nameMap.set(parentKey, new Set());\n }\n nameMap.get(parentKey).add(node.name);\n \n if (node.children && node.children.length > 0) {\n for (const child of node.children) {\n processNode(child, node.name);\n }\n }\n }\n \n for (const node of structure) {\n processNode(node, null);\n }\n \n return nameMap;\n}\n\nconst actualNameMap = buildNameMap(actualStructure);\n\nconsole.log('Actual name map:', JSON.stringify(\n Array.from(actualNameMap.entries()).map(([k, v]) => [k, Array.from(v)]),\n null, 2\n));\n\n// Function to check if a folder exists by name and parent\nfunction folderExists(folderName, parentName = null) {\n const parentKey = parentName || 'ROOT';\n const exists = actualNameMap.has(parentKey) && actualNameMap.get(parentKey).has(folderName);\n \n // Debug: log what we're checking\n if (!exists) {\n console.log(` Folder NOT found: name=\"${folderName}\", parent=\"${parentKey}\"`);\n if (actualNameMap.has(parentKey)) {\n console.log(` Available children in ${parentKey}:`, Array.from(actualNameMap.get(parentKey)));\n } else {\n console.log(` Parent ${parentKey} not found in actual structure`);\n }\n } else {\n console.log(` ✓ Folder found: name=\"${folderName}\", parent=\"${parentKey}\"`);\n }\n \n return exists;\n}\n\n// Function to recursively check folders and add exists field\nfunction checkFolders(desiredNode, parentName = null) {\n const exists = folderExists(desiredNode.name, parentName);\n \n console.log(`Checking folder: ${desiredNode.name}, parent: ${parentName || 'ROOT'}, exists: ${exists}`);\n \n const result = {\n name: desiredNode.name,\n exists: exists\n };\n \n if (desiredNode.description) {\n result.description = desiredNode.description;\n }\n \n // Check children - always include all children\n if (desiredNode.children && desiredNode.children.length > 0) {\n result.children = desiredNode.children.map(child => \n checkFolders(child, desiredNode.name)\n );\n }\n \n return result;\n}\n\n// Check all folders\nconst folderStatus = desiredStructure.map(node => checkFolders(node));\n\nconsole.log('Folder status:', JSON.stringify(folderStatus, null, 2));\n\nreturn [{ json: { folders: folderStatus } }];" + "jsCode": "// Code comes from src/governance/isc-gdrive/set-missing-folders.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, @@ -102,7 +102,7 @@ }, { "parameters": { - "jsCode": "// Flatten structure and produce a list of folders to create for THIS run.\n// - Only output folders where `exists === false` AND the parent already exists.\n// - Compute parentFolderId from the current Drive state (Build Actual Structure).\n//\n// On first run: only top-level folders are created.\n// On second run: their children are created.\n// On third run: grandchildren, etc.\n//\n// You keep running the workflow until it logs \"0 folders to create\".\n\n// --- CONFIG & INPUT ---\n\nconst rootFolderId = $('Set Configuration').first().json.rootFolderId;\nconst mainFolderId = rootFolderId;\n\nconsole.log('Using rootFolderId as mainFolderId:', mainFolderId);\n\n// This comes from \"Check Missing Folders\"\nconst folderStatusTree = $('Check Missing Folders').first().json.folders || [];\n\n// From \"Build Actual Structure\" (current Drive state)\nconst actualStructure = $('Build Actual Structure').first().json.actualStructure || [];\nconst allFolders = $('Build Actual Structure').first().json.allFolders || [];\n\nconsole.log('Actual structure nodes:', actualStructure.length);\nconsole.log('Total folders in allFolders:', allFolders.length);\n\n// --- BUILD path -> folderId MAP FROM CURRENT DRIVE STATE ---\n\n// We'll reconstruct full paths like \"00 – Governance/Charter\"\nconst pathToId = new Map();\n\nfunction buildPathMap(structure, parentPath = '', parentId = mainFolderId) {\n for (const node of structure) {\n const currentPath = parentPath ? `${parentPath}/${node.name}` : node.name;\n\n // Find the matching folder from allFolders by name + parentId\n const folder = allFolders.find(f => {\n const fParentId = f.parents && f.parents.length > 0 ? f.parents[0] : rootFolderId;\n return f.name === node.name && fParentId === parentId;\n });\n\n if (folder) {\n pathToId.set(currentPath, folder.id);\n // Recurse into children\n if (node.children && node.children.length > 0) {\n buildPathMap(node.children, currentPath, folder.id);\n }\n }\n }\n}\n\nbuildPathMap(actualStructure);\n\nconsole.log('Existing paths in Drive:');\nfor (const [p, id] of pathToId.entries()) {\n console.log(` ${p} -> ${id}`);\n}\n\n// --- FLATTEN DESIRED STRUCTURE (with exists flags) ---\n// We only output folders where:\n// - node.exists === false\n// - the parent \"exists\" right now (either root or in pathToId / actualStructure)\n\nfunction flattenForCreation(structure, parentPath = '', parentName = null, depth = 0, parentExists = true) {\n const result = [];\n\n for (const node of structure) {\n const currentPath = parentPath ? `${parentPath}/${node.name}` : node.name;\n const thisExists = node.exists === true;\n\n // Decide if THIS node should be created in this run\n // Only when it doesn't exist yet, and its parent exists.\n if (!thisExists && parentExists) {\n let parentFolderId;\n\n if (!parentPath) {\n // Top-level folder under the main/root folder\n parentFolderId = mainFolderId;\n } else {\n // Parent is some subfolder; look it up by its full path\n parentFolderId = pathToId.get(parentPath) || mainFolderId;\n }\n\n console.log(\n `Scheduling create: \"${currentPath}\" ` +\n `(depth ${depth}, parentPath=\"${parentPath}\", parentFolderId=${parentFolderId})`\n );\n\n result.push({\n name: node.name,\n description: node.description || '',\n path: currentPath,\n parentPath,\n parentName,\n depth,\n parentFolderId,\n });\n } else {\n console.log(\n `Skipping for now: \"${currentPath}\" (exists=${thisExists}, parentExists=${parentExists})`\n );\n }\n\n // Children: their parent \"exists\" if:\n // - this node already exists in Drive (thisExists === true), OR\n // - we have a path->id entry for it (i.e., it existed before this run).\n const childParentExists = thisExists || pathToId.has(currentPath);\n\n if (node.children && node.children.length > 0) {\n const childResults = flattenForCreation(\n node.children,\n currentPath,\n node.name,\n depth + 1,\n childParentExists,\n );\n result.push(...childResults);\n }\n }\n\n return result;\n}\n\nconst flattened = flattenForCreation(folderStatusTree);\n\n// Sort by depth so parents of this batch are before children of this batch\nflattened.sort((a, b) => a.depth - b.depth);\n\nconsole.log(`\\nFound ${flattened.length} folders to create in THIS run:`);\nflattened.forEach(f =>\n console.log(\n ` [depth ${f.depth}] ${f.path} (parentPath=\"${f.parentPath}\", parentFolderId=${f.parentFolderId})`,\n ),\n);\n\n// Output each folder as a separate item\nconst outputItems = flattened.map(folder => ({\n json: {\n ...folder,\n mainFolderId,\n rootFolderId,\n },\n}));\n\nconsole.log(`\\n=== OUTPUT: Returning ${outputItems.length} items ===`);\n\nreturn outputItems;\n" + "jsCode": "// Code comes from src/governance/isc-gdrive/flatten-folders-to-create.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, @@ -181,7 +181,7 @@ }, { "parameters": { - "jsCode": "const folders = $json.folders || [];\n\nfunction collectMissing(structure, parentPath = \"\") {\n let missing = [];\n for (const node of structure) {\n const currentPath = parentPath ? `${parentPath}/${node.name}` : node.name;\n if (node.exists === false) {\n missing.push(currentPath);\n }\n if (node.children && node.children.length > 0) {\n missing = missing.concat(collectMissing(node.children, currentPath));\n }\n }\n return missing;\n}\n\nconst missingList = collectMissing(folders);\nconst missingCount = missingList.length;\nconst missingFoldersText = missingList.join(\"\\n\");\n\nconsole.log(\"Missing folders:\", missingCount);\nconsole.log(\"Missing folders list:\", missingFoldersText);\n\nreturn [{ json: { folders, missingCount, hasMissing: missingCount > 0, missingFoldersText } }];" + "jsCode": "// Code comes from src/governance/isc-gdrive/check-missing-folders.js at build time." }, "id": "64a12f02-69c1-4ada-ba49-f60406d32d25", "name": "Check Missing Folders", @@ -272,7 +272,7 @@ }, { "parameters": { - "jsCode": "const folders = $json.folders || [];\nconst allFolders = $('Build Actual Structure').first().json.allFolders || [];\nconst rootFolderId = $('Set Configuration').first().json.rootFolderId;\n\nconst folderLookup = new Map();\nfor (const f of allFolders) {\n const parentId = f.parents && f.parents.length > 0 ? f.parents[0] : rootFolderId;\n folderLookup.set(`${parentId}::${f.name}`, f.id);\n}\n\nconst results = [];\n\nfunction collect(nodes, parentFolderId) {\n for (const node of nodes) {\n const key = `${parentFolderId}::${node.name}`;\n const folderId = folderLookup.get(key);\n\n if (folderId && node.description) {\n results.push({\n json: {\n folderId,\n name: node.name,\n description: node.description\n }\n });\n }\n\n if (folderId && node.children && node.children.length > 0) {\n collect(node.children, folderId);\n }\n }\n}\n\ncollect(folders, rootFolderId);\n\nconsole.log(`Found ${results.length} existing folders with descriptions to update`);\n\nreturn results.length > 0 ? results : [];" + "jsCode": "// Code comes from src/governance/isc-gdrive/collect-existing-folder-descriptions.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, diff --git "a/nodes/summit/Summit \342\200\224 Keynote Reachout.json" "b/nodes/summit/Summit \342\200\224 Keynote Reachout.json" index 65b1ce4..3085f00 100644 --- "a/nodes/summit/Summit \342\200\224 Keynote Reachout.json" +++ "b/nodes/summit/Summit \342\200\224 Keynote Reachout.json" @@ -77,7 +77,7 @@ }, { "parameters": { - "jsCode": "const staticData = $getWorkflowStaticData('global');\nstaticData.allMembers = [];\nreturn [{ json: { cursor: '' } }];" + "jsCode": "// Code comes from src/summit/summit-keynote-reachout/init-pagination.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, @@ -112,7 +112,7 @@ }, { "parameters": { - "jsCode": "const staticData = $getWorkflowStaticData('global');\nconst response = $input.first().json;\nif (response.members) {\n staticData.allMembers.push(...response.members);\n}\nconst nextCursor = response.response_metadata?.next_cursor || '';\nreturn [{ json: { cursor: nextCursor } }];" + "jsCode": "// Code comes from src/summit/summit-keynote-reachout/collect-members.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, @@ -158,7 +158,7 @@ }, { "parameters": { - "jsCode": "const staticData = $getWorkflowStaticData('global');\nconst allMembers = staticData.allMembers || [];\nreturn [{ json: { members: allMembers } }];" + "jsCode": "// Code comes from src/summit/summit-keynote-reachout/output-all-members.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, diff --git a/nodes/working-group-roles/ISC - Crier.json b/nodes/working-group-roles/ISC - Crier.json index bdb450b..25a9548 100644 --- a/nodes/working-group-roles/ISC - Crier.json +++ b/nodes/working-group-roles/ISC - Crier.json @@ -72,7 +72,7 @@ }, { "parameters": { - "jsCode": "const item = $input.first().json;\nconst d = item.utcDate;\nconst q = item.query;\nconst blocks = {\n blocks: [\n { type: 'section', text: { type: 'mrkdwn', text: ` Reminder: InnerSource Working Group call happens ${d.dayofweekname} at ${q.time} UTC :tada:\\n\\nThis is an excellent meeting for newcomers looking to learn about InnerSource. All are welcome to join!` } },\n { type: 'divider' },\n { type: 'section', text: { type: 'mrkdwn', text: `*This meeting's topic:*\\n\\n${q.topic}` } },\n { type: 'divider' },\n { type: 'section', fields: [\n { type: 'mrkdwn', text: `:spiral_calendar_pad: *Date:*\\n${d.dayofweekname}, ${d.monthname} ${d.ordinal}` },\n { type: 'mrkdwn', text: ':alarm_clock: *Time:*\\nMultiple time zones below' }\n ] },\n { type: 'section', text: { type: 'mrkdwn', text: `*Time Zones:*\\n${d.timeZonesText}` } },\n { type: 'divider' },\n { type: 'section', text: { type: 'mrkdwn', text: `:link: <${q.meeting_notes_url}>\\n:link: ` } },\n { type: 'actions', elements: [ { type: 'button', text: { type: 'plain_text', text: 'Join Meeting', emoji: true }, url: 'https://us06web.zoom.us/j/84987611486?pwd=Biw6cc9UwWI6FrM51Ugox10sClIP6n.1', style: 'danger' } ] }\n ]\n};\nreturn [{ json: { ...item, blocks } }];" + "jsCode": "// Code comes from src/working-group-roles/isc-crier/build-slack-blocks.js at build time." }, "type": "n8n-nodes-base.code", "typeVersion": 2, diff --git a/scripts/code-nodes.js b/scripts/code-nodes.js index 7432fd7..81c2b87 100644 --- a/scripts/code-nodes.js +++ b/scripts/code-nodes.js @@ -1,16 +1,19 @@ #!/usr/bin/env node -// Keeps each workflow's Code-node JavaScript in its own .js file under src/ -// and writes it back into the workflow JSON under nodes/. +// Keeps each workflow's Code-node JavaScript in its own .js file under src/. +// In the committed workflow JSON under nodes/, each Code node's jsCode is a one-line +// placeholder naming its source file, and the code is filled in whenever the workflow +// is published or built. // -// node scripts/code-nodes.js build write src/**/*.js into nodes/**/*.json -// node scripts/code-nodes.js check exit 1 if nodes/ differs from what build would write -// node scripts/code-nodes.js extract rewrite src/ from each Code node's jsCode, removing files whose node is gone +// node scripts/code-nodes.js render print the workflow with its code filled in +// node scripts/code-nodes.js build write every filled-in workflow to dist/ +// node scripts/code-nodes.js check exit 1 unless every Code node points at a source file and every source file is used +// node scripts/code-nodes.js extract move real code found in nodes/ into src/, leaving placeholders +// node scripts/code-nodes.js affected read changed paths (NUL-separated) on stdin, print the workflows they touch // -// A Code node's source lives at src///.js, +// Extract names a Code node's source file src///.js, // where each slug is the name lowercased with every run of non-alphanumeric characters turned into a hyphen. -// Build rewrites only the jsCode string of a node whose code changed, so the rest of -// the JSON stays byte-for-byte as it was and a diff shows only the changed node. +// Every edit replaces only jsCode strings, so the rest of the JSON stays byte-for-byte as it was. const fs = require('fs'); const path = require('path'); @@ -18,6 +21,13 @@ const path = require('path'); const ROOT = path.resolve(__dirname, '..'); const NODES_DIR = path.join(ROOT, 'nodes'); const SRC_DIR = path.join(ROOT, 'src'); +const DIST_DIR = path.join(ROOT, 'dist'); + +const PLACEHOLDER = /^\/\/ Code comes from (src\/\S+\.js) at build time\.$/; + +function placeholder(srcFile) { + return `// Code comes from ${rel(srcFile)} at build time.`; +} function walk(dir, ext) { if (!fs.existsSync(dir)) return []; @@ -62,6 +72,8 @@ function findJsCodeLiterals(raw) { } // Loads one workflow and pairs each Code node with its jsCode literal in the raw text. +// A node whose jsCode is a placeholder gets the source file it names; any other node +// holds real code and gets the source file extract would write it to. function loadWorkflow(file) { const raw = fs.readFileSync(file, 'utf8'); const workflow = JSON.parse(raw); @@ -78,17 +90,14 @@ function loadWorkflow(file) { path.relative(NODES_DIR, path.dirname(file)), slug(path.basename(file, '.json')) ); - const seen = new Map(); const nodes = codeNodes.map((node, i) => { - if (literals[i].value !== node.parameters.jsCode) { + const code = node.parameters.jsCode; + if (literals[i].value !== code) { throw new Error(`${rel(file)}: jsCode strings are not in node order near "${node.name}"`); } - const srcFile = path.join(workflowDir, `${slug(node.name)}.js`); - if (seen.has(srcFile)) { - throw new Error(`${rel(file)}: nodes "${seen.get(srcFile)}" and "${node.name}" both map to ${rel(srcFile)}; rename one`); - } - seen.set(srcFile, node.name); - return { name: node.name, code: node.parameters.jsCode, srcFile, literal: literals[i] }; + const m = code.match(PLACEHOLDER); + const srcFile = m ? path.join(ROOT, m[1]) : path.join(workflowDir, `${slug(node.name)}.js`); + return { name: node.name, code, isPlaceholder: !!m, srcFile, literal: literals[i] }; }); return { file, raw, nodes }; } @@ -108,7 +117,7 @@ function fromSource(text) { return text.replace(/\r\n/g, '\n').replace(/\n$/, ''); } -// Returns the workflow's raw text with every changed node's jsCode replaced. +// Returns the workflow's raw text with each node's jsCode string replaced by codeFor(node). function render(workflow, codeFor) { let out = ''; let pos = 0; @@ -121,77 +130,123 @@ function render(workflow, codeFor) { return out + workflow.raw.slice(pos); } -function readSources(workflows) { +function readSource(node) { + return fromSource(fs.readFileSync(node.srcFile, 'utf8')); +} + +// Lists everything that keeps the workflows from building; with all set, the workflows +// are the whole of nodes/ and a source file none of them uses is a problem too. +function problems(workflows, all = true) { const errors = []; - const expected = new Set(); + const used = new Map(); for (const wf of workflows) { for (const node of wf.nodes) { - expected.add(node.srcFile); - if (!fs.existsSync(node.srcFile)) { - errors.push(`${rel(wf.file)}: Code node "${node.name}" has no source file ${rel(node.srcFile)} (run extract)`); + const where = `${rel(wf.file)}: Code node "${node.name}"`; + if (!node.isPlaceholder) { + errors.push(`${where} holds its code in the JSON; run "make extract" to move it to src/`); + continue; + } + if (used.has(node.srcFile)) { + errors.push(`${where} points at ${rel(node.srcFile)}, which ${used.get(node.srcFile)} already uses`); } + used.set(node.srcFile, where); + if (!fs.existsSync(node.srcFile)) errors.push(`${where} points at ${rel(node.srcFile)}, which does not exist`); } } - for (const f of walk(SRC_DIR, '.js')) { - if (!expected.has(f)) errors.push(`${rel(f)} matches no Code node in nodes/`); - } - if (errors.length) { - errors.forEach((e) => console.error(`Error: ${e}`)); - process.exit(1); + for (const f of all ? walk(SRC_DIR, '.js') : []) { + if (!used.has(f)) errors.push(`${rel(f)} is used by no Code node in nodes/`); } + return errors; +} + +function failOn(errors) { + if (!errors.length) return; + errors.forEach((e) => console.error(`Error: ${e}`)); + process.exit(1); +} + +function renderOne(file) { + const wf = loadWorkflow(path.resolve(file)); + failOn(problems([wf], false)); + process.stdout.write(render(wf, readSource)); } -function build(write) { +function build() { const workflows = loadAll(); - readSources(workflows); - const stale = []; + failOn(problems(workflows)); + fs.rmSync(DIST_DIR, { recursive: true, force: true }); for (const wf of workflows) { - const out = render(wf, (node) => fromSource(fs.readFileSync(node.srcFile, 'utf8'))); - if (out === wf.raw) continue; - stale.push(rel(wf.file)); - if (write) fs.writeFileSync(wf.file, out); + const out = path.join(DIST_DIR, path.relative(NODES_DIR, wf.file)); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, render(wf, readSource)); } - if (write) { - console.log(stale.length ? `Built ${stale.join(', ')}` : 'Workflow JSON already matches src/.'); - return; - } - if (stale.length) { - stale.forEach((f) => console.error(`Error: ${f} does not match its src/ code; run "make build" and commit the result`)); - process.exit(1); - } - console.log('Workflow JSON matches src/.'); + console.log(`Built ${workflows.length} workflows into dist/.`); +} + +function check() { + failOn(problems(loadAll())); + console.log('Every Code node points at a source file in src/.'); } function extract() { const workflows = loadAll(); - const written = new Set(); + const claimed = new Map(); for (const wf of workflows) { for (const node of wf.nodes) { - // Build re-serializes jsCode with JSON.stringify, so check that the file extract is - // about to write would rebuild this node's jsCode literal byte for byte. + const owner = `${rel(wf.file)}: "${node.name}"`; + if (claimed.has(node.srcFile)) { + throw new Error(`${owner} and ${claimed.get(node.srcFile)} both map to ${rel(node.srcFile)}; rename one`); + } + claimed.set(node.srcFile, owner); + } + } + + let moved = 0; + for (const wf of workflows) { + const real = wf.nodes.filter((node) => !node.isPlaceholder); + if (!real.length) continue; + for (const node of real) { + // Publishing re-serializes the code with JSON.stringify, so check that the file + // extract is about to write would rebuild this node's jsCode literal byte for byte. const rebuilt = JSON.stringify(fromSource(toSource(node.code))); if (rebuilt !== wf.raw.slice(node.literal.start, node.literal.end)) { - throw new Error(`${rel(wf.file)}: build would not reproduce the jsCode of "${node.name}"`); + throw new Error(`${rel(wf.file)}: publishing would not reproduce the jsCode of "${node.name}"`); } fs.mkdirSync(path.dirname(node.srcFile), { recursive: true }); fs.writeFileSync(node.srcFile, toSource(node.code)); - written.add(node.srcFile); + moved++; } + fs.writeFileSync(wf.file, render(wf, (node) => (node.isPlaceholder ? node.code : placeholder(node.srcFile)))); } + for (const f of walk(SRC_DIR, '.js')) { - if (!written.has(f)) { + if (!claimed.has(f)) { fs.unlinkSync(f); console.log(`Removed ${rel(f)} (no matching Code node)`); } } - console.log(`Extracted ${written.size} Code nodes to src/.`); + console.log(`Moved ${moved} Code nodes' code into src/.`); +} + +// Publishing on merge sends the workflows a push touched: each changed workflow JSON, +// plus each workflow with a Code node whose source file changed. +function affected() { + const changed = new Set( + fs.readFileSync(0, 'utf8').split('\0').filter(Boolean).map((p) => path.join(ROOT, p)) + ); + const out = loadAll() + .filter((wf) => changed.has(wf.file) || wf.nodes.some((node) => changed.has(node.srcFile))) + .map((wf) => `${rel(wf.file)}\0`); + process.stdout.write(out.join('')); } -const command = process.argv[2]; -if (command === 'build') build(true); -else if (command === 'check') build(false); +const [command, arg] = process.argv.slice(2); +if (command === 'render' && arg) renderOne(arg); +else if (command === 'build') build(); +else if (command === 'check') check(); else if (command === 'extract') extract(); +else if (command === 'affected') affected(); else { - console.error('Usage: node scripts/code-nodes.js build|check|extract'); + console.error('Usage: node scripts/code-nodes.js render |build|check|extract|affected'); process.exit(1); } diff --git a/scripts/update-workflow.sh b/scripts/update-workflow.sh index 8c38b47..5bc201b 100755 --- a/scripts/update-workflow.sh +++ b/scripts/update-workflow.sh @@ -28,10 +28,17 @@ fi echo "Updating Workflow ID: $WORKFLOW_ID" -# Create a temporary file with the cleaned JSON payload +# Create a temporary file with the cleaned JSON payload, with each Code node's +# code filled in from src/ # Select only allowed fields and remove null values (active and tags are read-only) +set -o pipefail CLEAN_JSON_FILE=$(mktemp) -jq '{name, nodes, connections, settings, staticData} | with_entries(select(.value != null))' "$WORKFLOW_FILE" > "$CLEAN_JSON_FILE" +if ! node "$(dirname "$0")/code-nodes.js" render "$WORKFLOW_FILE" \ + | jq '{name, nodes, connections, settings, staticData} | with_entries(select(.value != null))' > "$CLEAN_JSON_FILE"; then + echo "Error: Could not build the workflow from $WORKFLOW_FILE and src/." + rm "$CLEAN_JSON_FILE" + exit 1 +fi # Update the workflow # The API expects the workflow JSON object in the body. From 6be3b00ce1a565b15a561dc12d6cee6c20088fae Mon Sep 17 00:00:00 2001 From: Russ Rutledge Date: Tue, 27 Oct 2026 17:01:05 -0500 Subject: [PATCH 3/3] Preview on each pull request how the built workflows differ from the base branch A new preview job builds the workflows publishing would send from the pull request and from its base branch, and lists each one as identical or names what changed, on the run's summary page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AEavKGR3wFFUQXR9W16mSQ --- .github/workflows/check-code-nodes.yml | 24 ++++++++++++ USAGE.md | 1 + scripts/code-nodes.js | 51 +++++++++++++++++++++++++- 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/.github/workflows/check-code-nodes.yml b/.github/workflows/check-code-nodes.yml index 30de8c8..19d41b2 100644 --- a/.github/workflows/check-code-nodes.yml +++ b/.github/workflows/check-code-nodes.yml @@ -16,3 +16,27 @@ jobs: - name: Check run: node scripts/code-nodes.js check + + # Builds what publishing would send to n8n from this pull request and from its base + # branch, and writes the difference to the run's summary page for reviewers. + preview: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Compare with the base branch + run: | + set -euo pipefail + node scripts/code-nodes.js build + git worktree add "$RUNNER_TEMP/base" "$BASE_SHA" + if [ -f "$RUNNER_TEMP/base/scripts/code-nodes.js" ]; then + node "$RUNNER_TEMP/base/scripts/code-nodes.js" build + else + cp -r "$RUNNER_TEMP/base/nodes" "$RUNNER_TEMP/base/dist" + fi + node scripts/code-nodes.js compare "$RUNNER_TEMP/base/dist" dist | tee -a "$GITHUB_STEP_SUMMARY" diff --git a/USAGE.md b/USAGE.md index 1f1ee7b..a693984 100644 --- a/USAGE.md +++ b/USAGE.md @@ -27,6 +27,7 @@ To change a Code node, edit its file under `src/` and commit it. `make build` writes every workflow with its code filled in to `dist/`, ready to import into an n8n instance by hand. The `Check Code nodes point at src/` GitHub Action fails a pull request in which a Code node holds code instead of naming a file, names a file that doesn't exist, or a file under `src/` belongs to no Code node; run `make check` to see the same result locally. +On a pull request, the same Action's `preview` job builds what publishing would send to n8n from the pull request and from its base branch, and lists each workflow as identical or names what changed, on the run's summary page. When a workflow comes from an export of the n8n editor, its Code nodes hold their real code. Copy the export over the workflow's file under `nodes/` and run `make extract`, which moves each node's code into `src/` and puts the one-line comment back in the JSON. diff --git a/scripts/code-nodes.js b/scripts/code-nodes.js index 81c2b87..8017c27 100644 --- a/scripts/code-nodes.js +++ b/scripts/code-nodes.js @@ -10,6 +10,7 @@ // node scripts/code-nodes.js check exit 1 unless every Code node points at a source file and every source file is used // node scripts/code-nodes.js extract move real code found in nodes/ into src/, leaving placeholders // node scripts/code-nodes.js affected read changed paths (NUL-separated) on stdin, print the workflows they touch +// node scripts/code-nodes.js compare report how two built dist/ folders differ, as markdown // // Extract names a Code node's source file src///.js, // where each slug is the name lowercased with every run of non-alphanumeric characters turned into a hyphen. @@ -240,13 +241,59 @@ function affected() { process.stdout.write(out.join('')); } -const [command, arg] = process.argv.slice(2); +// Prints a markdown report of how each built workflow in headDir differs from its +// counterpart in baseDir. +function compare(baseDir, headDir) { + const files = (dir) => new Set(walk(path.resolve(dir), '.json').map((f) => path.relative(path.resolve(dir), f))); + const base = files(baseDir); + const head = files(headDir); + const read = (dir, f) => fs.readFileSync(path.join(dir, f), 'utf8').replace(/\r\n/g, '\n'); + const codeOf = (wf) => new Map((wf.nodes || []).map((n) => [n.name, n.parameters && n.parameters.jsCode])); + const withoutCode = (wf) => JSON.stringify({ + ...wf, + nodes: (wf.nodes || []).map((n) => ({ ...n, parameters: { ...n.parameters, jsCode: undefined } })), + }); + + const rows = [...new Set([...base, ...head])].sort().map((f) => { + const name = f.split(path.sep).join('/'); + if (!base.has(f)) return [name, 'new workflow']; + if (!head.has(f)) return [name, 'removed from the repo']; + const before = read(baseDir, f); + const after = read(headDir, f); + if (before === after) return [name, 'identical']; + const [b, a] = [JSON.parse(before), JSON.parse(after)]; + const [bCode, aCode] = [codeOf(b), codeOf(a)]; + const changes = []; + const nodeNames = [...new Set([...bCode.keys(), ...aCode.keys()])]; + const codeChanged = nodeNames.filter((n) => bCode.has(n) && aCode.has(n) && bCode.get(n) !== aCode.get(n)); + const added = nodeNames.filter((n) => !bCode.has(n)); + const removed = nodeNames.filter((n) => !aCode.has(n)); + if (codeChanged.length) changes.push(`code changed in ${codeChanged.map((n) => `"${n}"`).join(', ')}`); + if (added.length) changes.push(`nodes added: ${added.map((n) => `"${n}"`).join(', ')}`); + if (removed.length) changes.push(`nodes removed: ${removed.map((n) => `"${n}"`).join(', ')}`); + if (withoutCode(b) !== withoutCode(a) && !added.length && !removed.length) changes.push('changes outside the Code nodes\' code'); + if (!changes.length) changes.push('formatting changed'); + return [name, changes.join('; ')]; + }); + + const changed = rows.filter(([, status]) => status !== 'identical').length; + console.log('## Built workflows compared with the base branch\n'); + console.log(changed + ? `${changed} of ${rows.length} workflows differ from the base branch.\n` + : `All ${rows.length} workflows match the base branch.\n`); + console.log('| Workflow | Compared with the base branch |'); + console.log('|---|---|'); + rows.forEach(([name, status]) => console.log(`| ${name} | ${status} |`)); +} + +const [command, arg, arg2] = process.argv.slice(2); if (command === 'render' && arg) renderOne(arg); +else if (command === 'compare' && arg && arg2) compare(arg, arg2); else if (command === 'build') build(); else if (command === 'check') check(); else if (command === 'extract') extract(); else if (command === 'affected') affected(); else { - console.error('Usage: node scripts/code-nodes.js render |build|check|extract|affected'); + console.error('Usage: node scripts/code-nodes.js render |build|check|extract|affected|compare '); process.exit(1); }