Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
module.exports = {
root: true,
env: { es2022: true },
parserOptions: { ecmaVersion: 2022 },
extends: ['eslint:recommended'],
rules: {
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
overrides: [
{
files: [
'.eslintrc.cjs',
'src/**/*.js',
'test/**/*.js',
'test-support/**/*.cjs',
],
env: { node: true },
globals: {
fetch: 'readonly',
FormData: 'readonly',
AbortSignal: 'readonly',
},
},
{
files: ['public/scripts/**/*.js'],
env: { browser: true },
},
{
files: ['public/scripts/text-parser.js'],
env: { node: true },
},
{
files: [
'public/scripts/publish.js',
'public/scripts/upload.js',
'public/scripts/hide-reply.js',
],
globals: {
processFormAsync: 'readonly',
onAsyncRequestStarting: 'readonly',
onAsyncRequestEnded: 'readonly',
},
},
],
};
37 changes: 37 additions & 0 deletions .github/workflows/code-checks.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Code Checks

on:
pull_request:
push:
branches: [main]

permissions:
contents: read

jobs:
checks:
name: Checks (Node ${{ matrix.node }})
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
node: [24, 26]
steps:
- name: Check Out Code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set Up Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ matrix.node }}
package-manager-cache: false
- name: Install Dependencies
run: npm install --ignore-scripts --no-audit --no-fund --package-lock=false
- name: Lint
run: npm run lint
- name: Check Formatting
run: npm run format:check
- name: Run Mocked Tests
run: npm test
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,20 @@ Note: If you are using devcontainers, ensure that containers are enabled and sup
- Once the Sample App starts running, go to https://threads-sample.meta:8000 to test the workflow.
- If you are using a different domain or port then replace those values accordingly.

## Tests
## Checks

Run `npm test` to check search modes, filters, and pagination with mocked API responses. These tests do not call the Threads API.
Run lint, formatting, and tests before opening a pull request:

```sh
npm install --ignore-scripts --no-audit --no-fund --package-lock=false
npm run lint
npm run format:check
npm test
```

Tests use mocked API responses. They do not call the Threads API.

GitHub Actions runs these checks for pull requests. It also runs them for pushes to `main`. Both Node.js 24 and 26 are covered.

## License

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"scripts": {
"start": "node ./src/index.js",
"test": "node --test",
"lint": "eslint --max-warnings 0 .eslintrc.cjs src public/scripts test && if [ -d test-support ]; then eslint --max-warnings 0 --ext .cjs test-support; fi",
"format:check": "prettier --check .",
"format:write": "prettier --write ."
},
Expand Down
2 changes: 2 additions & 0 deletions public/scripts/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* LICENSE file in the root directory of this source tree.
*/

/* exported processFormAsync */

let loadingOverlay;

document.addEventListener('DOMContentLoaded', () => {
Expand Down
2 changes: 1 addition & 1 deletion public/scripts/hide-reply.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ document.addEventListener('DOMContentLoaded', async () => {
alert('An error occurred while hiding/unhiding the reply.');
}
} catch (e) {
console.error('There was an error:', error);
console.error('There was an error while hiding the reply.');
alert('error while hiding reply');
} finally {
onAsyncRequestEnded();
Expand Down
14 changes: 10 additions & 4 deletions public/scripts/text-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ function extractSpoilerInfo(text) {
}

// Add text before the spoiler marker to cleaned text
const textBeforeMarker = text.substring(searchPosition, startMarkerIndex);
const textBeforeMarker = text.substring(
searchPosition,
startMarkerIndex
);
cleanedText += textBeforeMarker;
currentPosition += textBeforeMarker.length;

Expand All @@ -48,11 +51,14 @@ function extractSpoilerInfo(text) {
}

// Extract spoiler content
const spoilerContent = text.substring(contentStartIndex, endMarkerIndex);
const spoilerContent = text.substring(
contentStartIndex,
endMarkerIndex
);

// Record spoiler info
textEntities.push({
entity_type: "SPOILER",
entity_type: 'SPOILER',
offset: currentPosition.toString(),
length: spoilerContent.length.toString(),
});
Expand All @@ -67,6 +73,6 @@ function extractSpoilerInfo(text) {

return {
textEntities: textEntities,
text: cleanedText
text: cleanedText,
};
}
2 changes: 1 addition & 1 deletion public/scripts/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ document.addEventListener('DOMContentLoaded', async () => {
});

const mediaTypeSelectElem = div.querySelector('select');
mediaTypeSelectElem.addEventListener('change', async (e) => {
mediaTypeSelectElem.addEventListener('change', async () => {
await updateMediaType(
attachmentsList.children.length,
attachmentsList
Expand Down
56 changes: 39 additions & 17 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ app.use(function protectAgainstCsrf(req, res, next) {
});

const JSON_TOKEN_PATTERN =
/"(?:[^"\\]|\\.)*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}\[\]:,]/g;
/"(?:[^"\\]|\\.)*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g;

function parseUserIdResponse(text) {
const stack = [];
Expand Down Expand Up @@ -909,9 +909,9 @@ app.post(
}

if (text.includes(spoilerMarker)) {
parsedInput = textParser.extractSpoilerInfo(text);
processedText = parsedInput.text;
textEntites = parsedInput.textEntities;
const parsedInput = textParser.extractSpoilerInfo(text);
const processedText = parsedInput.text;
const textEntites = parsedInput.textEntities;
params[PARAMS__TEXT] = processedText;
params[PARAMS_TEXT_ENTITES] = JSON.stringify(textEntites);
} else {
Expand Down Expand Up @@ -1581,27 +1581,49 @@ app.get('/threads/:threadId/conversation', loggedInUserChecker, (req, res) => {
app.post('/manage_reply/:replyId', upload.array(), async (req, res) => {
const { replyId } = req.params;
const { hide } = req.query;
if (
typeof replyId !== 'string' ||
!/^[1-9]\d*$/.test(replyId) ||
replyId.trim() !== replyId
) {
return res.status(400).json({
error: true,
message: 'The reply ID is invalid.',
});
}

const params = {};
if (hide) {
params[PARAMS__HIDE] = hide === 'true';
}

const hideReplyUrl = buildGraphAPIURL(
`${replyId}/manage_reply`,
{},
req.session.access_token
);

try {
response = await axios.post(hideReplyUrl, params, {
const hideReplyUrl = new URL(
buildGraphAPIURL(`${replyId}/manage_reply`, {}, null)
);
if (
hideReplyUrl.origin !== 'https://graph.threads.com' ||
hideReplyUrl.username ||
hideReplyUrl.password ||
hideReplyUrl.hash
) {
throw new Error('Invalid reply request URL.');
}
if (req.session.access_token) {
hideReplyUrl.searchParams.append(
PARAMS__ACCESS_TOKEN,
req.session.access_token
);
}
await axios.post(hideReplyUrl.toString(), params, {
httpsAgent: agent,
maxRedirects: 0,
});
} catch (e) {
console.error(e?.message);
return res.status(e?.response?.status ?? 500).json({
} catch {
console.error('Unable to update the reply.');
return res.status(502).json({
error: true,
message: `Error while hiding reply: ${e}`,
message: 'Unable to update the reply. Try again.',
});
}

Expand Down Expand Up @@ -2389,11 +2411,11 @@ function addAttachmentFields(target, attachmentType, url, altText) {
if (attachmentType === 'Image') {
target.media_type = MEDIA_TYPE__IMAGE;
target.image_url = url;
target.alt_text = altText;
target[PARAMS__ALT_TEXT] = altText;
} else if (attachmentType === 'Video') {
target.media_type = MEDIA_TYPE__VIDEO;
target.video_url = url;
target.alt_text = altText;
target[PARAMS__ALT_TEXT] = altText;
}
}

Expand Down
2 changes: 1 addition & 1 deletion test/app-scoped-user-id.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ test('OAuth keeps the exact app-scoped ID through token exchange and rejects amb
assert.equal(new URL(url).pathname, '/oauth/access_token');
return {
data: transform(
`{"access_token":"synthetic-short-token","user_id":${userId},"data":{"user_id":"999"},"note":"\\\"user_id\\\":123"}`,
`{"access_token":"synthetic-short-token","user_id":${userId},"data":{"user_id":"999"},"note":"\\"user_id\\":123"}`,
options
),
};
Expand Down
Loading