Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stable @tma.js/launch-params #173

Merged
merged 52 commits into from
Nov 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
749640f
chore(readme): remove unused links
heyqbnk Nov 5, 2023
a3eda5b
feat(postEvent): log function call
heyqbnk Nov 5, 2023
fe19f38
feat(keys): add new v6.10 palette keys
heyqbnk Nov 5, 2023
e860176
feat(serialize): generalize function code
heyqbnk Nov 5, 2023
7aaeb15
tests(parse,serialize,themeParams): add missing tests
heyqbnk Nov 5, 2023
4767cc2
refactor(serialize): refactor function code a bit
heyqbnk Nov 5, 2023
f6342eb
fix(errors): reuse unexpectedTypeError in parsers
heyqbnk Nov 9, 2023
84d53c7
refactor(parsing error): replace with 2 new error classes
heyqbnk Nov 9, 2023
dac4b58
refactor(package): allow usage of parser type names. Refactor utiliti…
heyqbnk Nov 9, 2023
cb7dcb1
tests(searchParams): fix tests throwing errors
heyqbnk Nov 9, 2023
d334fbe
feat(types): extend launch params type. Implement launch data type
heyqbnk Nov 10, 2023
f3d35aa
fix(storage): make retrieveFromStorage unsafer. Add methods comments
heyqbnk Nov 10, 2023
f0025ff
feat(serialize): serialize new parameters
heyqbnk Nov 10, 2023
627c9a8
feat(functions): implement retrieveLaunchData
heyqbnk Nov 10, 2023
2edf2a9
feat(functions): implement retrieveFromPerformance
heyqbnk Nov 10, 2023
ea82c1e
feat(functions): implement retrieveFromLocation
heyqbnk Nov 10, 2023
27d4d17
feat(functions): implement retrieveCurrent
heyqbnk Nov 10, 2023
38d8ea2
feat(functions): implement computeLaunchData
heyqbnk Nov 10, 2023
0a0bbcc
feat(functions): implement computePageReload
heyqbnk Nov 10, 2023
519c572
feat(functions): implement getFirstNavigationEntry
heyqbnk Nov 10, 2023
31625f5
feat(launchParams): implement botInline and showSettings properties. …
heyqbnk Nov 10, 2023
e73eba3
chore(parse): add thrown error jsdoc
heyqbnk Nov 10, 2023
e52d501
feat(index): export new utilities
heyqbnk Nov 10, 2023
dfbe89e
tests(all): implement new tests, rework old
heyqbnk Nov 10, 2023
d30e207
chore(deps): add test-utils dep
heyqbnk Nov 10, 2023
784df89
feat(packages): implement test utilities package
heyqbnk Nov 10, 2023
a8ba4e2
fix(exports): re-export createValueParserGenerator
heyqbnk Nov 10, 2023
b4abde1
feat(parsers): add type names
heyqbnk Nov 10, 2023
75809fc
tests(all): actualize tests
heyqbnk Nov 10, 2023
78de926
chore(deps): add test-utils dep
heyqbnk Nov 10, 2023
edf82f7
feat(themeParams): add parser type name
heyqbnk Nov 10, 2023
51e14b8
chore(imports): createValueParserGen -> createValueParserGenerator
heyqbnk Nov 10, 2023
1717eaa
chore(lock): update lock
heyqbnk Nov 10, 2023
9e85485
feat(sdk): actualize list of palette keys
heyqbnk Nov 10, 2023
6b97921
docs(changeset): - Implement `ParsingError` and `ParseSchemaFieldErro…
heyqbnk Nov 10, 2023
025ba0d
chore(changeset): update parser changeset
heyqbnk Nov 10, 2023
7c1c7a2
docs(changeset): - Implement new 6.10 palette keys
heyqbnk Nov 10, 2023
578209a
tests(mocks): fix incorrect mocks
heyqbnk Nov 11, 2023
25e718d
feat(computeLaunchData,retrieveLaunchData): allow passing previous an…
heyqbnk Nov 11, 2023
dcaf9f4
feat(env): add isTMA function. Replace retrieveLaunchParams with retr…
heyqbnk Nov 11, 2023
0bf3d2a
refactor(launch-params): remove launch parameters utilities
heyqbnk Nov 11, 2023
12a62ae
refactor(launch-params): remove launch parameters utilities
heyqbnk Nov 11, 2023
7803e82
refactor(init): simplify initialization in context of launch params e…
heyqbnk Nov 11, 2023
2b7d48f
tests(launch-params): remove module tests
heyqbnk Nov 11, 2023
021fb88
chore(changeset): specify more information in update for launch params
heyqbnk Nov 11, 2023
ea04366
chore(mobile): move hashtag to the right side
heyqbnk Nov 11, 2023
9c2da51
chore(readme): update readme
heyqbnk Nov 11, 2023
dbc1c70
feat(packages): add @tma.js/launch-params page
heyqbnk Nov 11, 2023
7a6549c
docs(changeset): - Add `logger.log` call in postEvent
heyqbnk Nov 11, 2023
92848a6
docs(changeset): - Specify parsers type names
heyqbnk Nov 12, 2023
44ed697
docs(changeset): - Add new types of errors
heyqbnk Nov 12, 2023
a4fd5b8
docs(changeset): - Actualize theme parameters list
heyqbnk Nov 12, 2023
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
7 changes: 7 additions & 0 deletions .changeset/afraid-dingos-arrive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@tma.js/parsing": minor
---

- Add new types of errors
- Add ability to specify parser type name
- Improve schema parsing be throwing more accurate errors
11 changes: 11 additions & 0 deletions .changeset/angry-dragons-develop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@tma.js/parsing": major
---

This is the first `@tma.js/parsing` package major update.

- Implement `ParsingError` and `ParseSchemaFieldError` classes to provide better understanding of the error
- Allow specifying parser type name to improve error messages
- Fix minor problems in throwing errors
- Actualize tests
- Set type names for all built-in types
5 changes: 5 additions & 0 deletions .changeset/gorgeous-moose-reflect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tma.js/bridge": patch
---

- Add `logger.log` call in postEvent
5 changes: 5 additions & 0 deletions .changeset/lemon-foxes-obey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tma.js/init-data": patch
---

- Specify parsers type names
7 changes: 7 additions & 0 deletions .changeset/proud-mails-march.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@tma.js/theme-params": minor
---

- Implement new 6.10 palette keys
- Add parser type name
- Allow specifying previous and current launch parameters in launch data computation methods
6 changes: 6 additions & 0 deletions .changeset/silent-pens-heal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@tma.js/sdk": minor
---

- Actualize theme parameters list
- Simplify init process
10 changes: 0 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
[code-badge]: https://img.shields.io/badge/source-black?logo=github

[docs-badge]: https://img.shields.io/badge/documentation-blue?logo=gitbook&logoColor=white

[react-badge]: https://img.shields.io/badge/React-244654?logo=react&logoColor=61DAFB

[solid-badge]: https://img.shields.io/badge/Solid-203A59?logo=solid&logoColor=38659F

[node-badge]: https://img.shields.io/badge/Node-1f491f?logo=node.js&logoColor=339933

# @tma.js

Mono-repository, containing all the packages, connected with comfortable and safe TypeScript
Expand Down
1 change: 1 addition & 0 deletions apps/docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export default defineConfig({
text: '@tma.js/init-data-node',
link: '/packages/typescript/tma-js-init-data-node',
},
{ text: '@tma.js/launch-params', link: '/packages/typescript/tma-js-launch-params' },
{
text: '@tma.js/sdk',
collapsed: true,
Expand Down
23 changes: 23 additions & 0 deletions apps/docs/.vitepress/theme/custom.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@media (max-width: 768px) {
/* In mobile version we would like to move hashtag ("#") to the right side of section title. */
.vp-doc h1,
.vp-doc h2,
.vp-doc h3,
.vp-doc h4,
.vp-doc h5,
.vp-doc h6 {
padding-right: 1em;
}

.vp-doc h1 .header-anchor,
.vp-doc h2 .header-anchor,
.vp-doc h3 .header-anchor,
.vp-doc h4 .header-anchor,
.vp-doc h5 .header-anchor,
.vp-doc h6 .header-anchor {
left: auto;
top: auto;
bottom: 0;
margin-left: .3em;
}
}
4 changes: 4 additions & 0 deletions apps/docs/.vitepress/theme/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import DefaultTheme from 'vitepress/theme';
import './custom.css';

export default DefaultTheme;
204 changes: 204 additions & 0 deletions apps/docs/packages/typescript/tma-js-launch-params.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# @tma.js/launch-params

[npm-link]: https://npmjs.com/package/@tma.js/launch-params

[npm-shield]: https://img.shields.io/npm/v/@tma.js/launch-params?logo=npm

![[npm-link]][npm-shield]

Provides utilities to work with Telegram Mini
Apps [launch parameters](../../launch-parameters/common-information.md).

## Installation

::: code-group

```bash [pnpm]
pnpm i @tma.js/launch-params
```

```bash [npm]
npm i @tma.js/launch-params
```

```bash [yarn]
yarn add @tma.js/launch-params
```

:::

## Parsing

To parse value as launch parameters, package provides method `parse` and parser `launchParams`
which is being utilized by `parse`.

Method and parser accept query parameters presented as a string or an instance of `URLSearchParams`,
returning the `LaunchParams` interface. It throws an error if the passed data is invalid.

::: code-group

```typescript [Usage example]
import { parse, launchParams } from '@tma.js/launch-params';

const searchParams = new URLSearchParams([
['tgWebAppVersion', '6.7'],
['tgWebAppPlatform', 'tdekstop'],
['tgWebAppBotInline', '1'],
['tgWebAppData', new URLSearchParams([
['query_id', 'AAHdF6IQAAAAAN0XohAOqR8k'],
['user', JSON.stringify({
id: 279058397,
first_name: 'Vladislav',
last_name: 'Kibenko',
username: 'vdkfrost',
language_code: 'ru',
is_premium: true,
allows_write_to_pm: true,
})],
['auth_date', '1691441944'],
['hash', 'abc'],
]).toString()],
['tgWebAppThemeParams', JSON.stringify({
bg_color: '#17212b',
button_color: '#5288c1',
button_text_color: '#ffffff',
hint_color: '#708499',
link_color: '#6ab3f3',
secondary_bg_color: '#232e3c',
text_color: '#f5f5f5',
})],
]);

const lp = parse(searchParams);
// or
const lp = launchParams().parse(searchParams);
```

```typescript [Expected result]
const result = {
botInline: true,
version: '6.7',
platform: 'tdesktop',
themeParams: {
backgroundColor: '#17212b',
buttonColor: '#5288c1',
buttonTextColor: '#ffffff',
hintColor: '#708499',
linkColor: '#6ab3f3',
secondaryBackgroundColor: '#232e3c',
textColor: '#f5f5f5',
},
initDataRaw: 'query_id=AAHdF6IQAAAAAN0XohAOqR8k&user=%7B%22id%22%3A279058397%2C%22first_name%22%3A%22Vladislav%22%2C%22last_name%22%3A%22Kibenko%22%2C%22username%22%3A%22vdkfrost%22%2C%22language_code%22%3A%22ru%22%2C%22is_premium%22%3Atrue%2C%22allows_write_to_pm%22%3Atrue%7D&auth_date=1691441944&hash=abc',
initData: {
queryId: 'AAHdF6IQAAAAAN0XohAOqR8k',
authDate: new Date(1691441944000),
hash: 'abc',
user: {
id: 279058397,
firstName: 'Vladislav',
lastName: 'Kibenko',
username: 'vdkfrost',
languageCode: 'ru',
isPremium: true,
allowsWriteToPm: true,
},
},
};
```

:::

## Serializing

To convert the launch parameters object representation to a string, developers should use
the `serialize` function:

```typescript
import { serialize } from '@tma.js/launch-params';

serialize({
version: '6.7',
platform: 'tdesktop',
themeParams: {
backgroundColor: '#17212b',
buttonColor: '#5288c1',
buttonTextColor: '#ffffff',
hintColor: '#708499',
linkColor: '#6ab3f3',
secondaryBackgroundColor: '#232e3c',
textColor: '#f5f5f5',
},
});

// Result:
// tgWebAppVersion=6.7&tgWebAppPlatform=tdesktop&tgWebAppThemeParams=%7B%22bg_color%22%3A%22%2317212b%22%2C%22button_color%22%3A%22%235288c1%22%2C%22button_text_color%22%3A%22%23ffffff%22%2C%22hint_color%22%3A%22%23708499%22%2C%22link_color%22%3A%22%236ab3f3%22%2C%22secondary_bg_color%22%3A%22%23232e3c%22%2C%22text_color%22%3A%22%23f5f5f5%22%7D
```

## Retrieving

This package enables the extraction of launch parameters from the current environment using
the [retrieveFromLocation](#retrievefromlocation), [retrieveFromPerformance](#retrievefromperformance),
and [retrieveFromStorage](#retrievefromstorage) functions. Developer is also able
to use `retrieveLaunchData` to surely extract launch parameters and determine if current page was
reloaded. Each of these functions throws an error if the source contains invalid data.

### `retrieveLaunchData`

Extracts actual launch parameters and page reload flag.

```typescript
import { retrieveLaunchData } from '@tma.js/launch-params';

const { launchParams, isPageReload } = retrieveLaunchData();
```

::: info

This function is more likely to be used by developers because it offers a stable way of retrieving
the actual launch parameters.

:::

### `retrieveFromStorage`

Extracts launch parameters from `sessionStorage`. This method expects that launch parameters have
been saved in the `sessionStorage` via the `saveToStorage` method.

```typescript
import { retrieveFromStorage, saveToStorage } from '@tma.js/launch-params';

saveToStorage({
initData: {
authDate: new Date(16552413000),
hash: 'hash',
},
initDataRaw: 'auth_date=16552413&hash=hash',
themeParams: {},
version: '7.0',
platform: 'macos',
});

const launchParameters = retrieveFromStorage();
```

### `retrieveFromLocation`

Extracts launch parameters from `window.location.hash`:

```typescript
import { retrieveFromLocation } from '@tma.js/launch-params';

const launchParameters = retrieveFromLocation();
```

### `retrieveFromPerformance`

Extracts launch parameters from `window.performance`. This function allows retrieving launch
parameters
using [performance navigation entries](https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings).

```typescript
import { retrieveFromPerformance } from '@tma.js/launch-params';

const launchParameters = retrieveFromPerformance();
```
10 changes: 6 additions & 4 deletions packages/bridge/src/events/parsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
boolean,
json,
rgb,
createValueParserGen,
createValueParserGenerator,
} from '@tma.js/parsing';

import type {
Expand All @@ -22,9 +22,11 @@ function isNullOrUndefined(value: unknown): boolean {
const rgbOptional = rgb().optional();
const num = number();

const windowWidthParser = createValueParserGen((value) => (value === null || value === undefined
? window.innerWidth
: num.parse(value)));
const windowWidthParser = createValueParserGenerator(
(value) => (value === null || value === undefined
? window.innerWidth
: num.parse(value)),
);

/**
* Parses incoming value as ThemeChangedPayload.
Expand Down
14 changes: 6 additions & 8 deletions packages/bridge/src/methods/postEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import {
hasExternalNotify,
hasWebviewProxy,
} from '../env.js';
import { targetOrigin as globalTargetOrigin } from '../globals.js';

import { logger, targetOrigin as globalTargetOrigin } from '../globals.js';
import type {
EmptyMethodName,
MethodName,
Expand All @@ -30,8 +29,7 @@ export type PostEvent = typeof postEvent;
* @param eventType - event name.
* @param params - event parameters.
* @param options - posting options.
* @throws {Error} Bridge could not determine current
* environment and possible way to send event.
* @throws {Error} Bridge could not determine current environment and possible way to send event.
*/
export function postEvent<E extends NonEmptyMethodName>(
eventType: E,
Expand All @@ -44,8 +42,7 @@ export function postEvent<E extends NonEmptyMethodName>(
* accepts only events, which require arguments.
* @param eventType - event name.
* @param options - posting options.
* @throws {Error} Bridge could not determine current
* environment and possible way to send event.
* @throws {Error} Bridge could not determine current environment and possible way to send event.
*/
export function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;

Expand Down Expand Up @@ -74,6 +71,8 @@ export function postEvent(
}
const { targetOrigin = globalTargetOrigin() } = postOptions;

logger.log(`Calling method "${eventType}"`, eventData);

// Telegram Web.
if (isIframe()) {
window.parent.postMessage(JSON.stringify({
Expand All @@ -95,8 +94,7 @@ export function postEvent(
return;
}

// Otherwise current environment is unknown, and we are not able to send
// event.
// Otherwise current environment is unknown, and we are not able to send event.
throw new Error(
'Unable to determine current environment and possible way to send event.',
);
Expand Down
3 changes: 2 additions & 1 deletion packages/init-data/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@
"devDependencies": {
"tsconfig": "workspace:*",
"eslint-config-custom": "workspace:*",
"build-utils": "workspace:*"
"build-utils": "workspace:*",
"test-utils": "workspace:*"
},
"publishConfig": {
"access": "public"
Expand Down
2 changes: 2 additions & 0 deletions packages/init-data/src/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,7 @@ export function chat() {
from: 'photo_url',
},
username: string().optional(),
}, {
type: 'Chat',
});
}
Loading