chore: mark methods as js-only, add python-specific methods (#4938)

This commit is contained in:
Pavel Feldman 2021-01-07 16:12:25 -08:00 коммит произвёл GitHub
Родитель e56832b646
Коммит 54c06a1b45
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
18 изменённых файлов: 160 добавлений и 94 удалений

Просмотреть файл

@ -1,10 +1,7 @@
# class: Browser # class: Browser
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
A Browser is created when Playwright connects to a browser instance, either through [`method: BrowserType.launch`] or A Browser is created via [`method: BrowserType.launch`]. An example of using a [Browser] to create a [Page]:
[`method: BrowserType.connect`].
An example of using a [Browser] to create a [Page]:
```js ```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'. const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@ -17,9 +14,8 @@ const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
})(); })();
``` ```
See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that [`method: See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that
BrowserType.connect`] and [`method: BrowserType.launch`] always return a specific browser instance, based on the [`method: BrowserType.launch`] always returns a specific browser instance, based on the browser being launched.
browser being connected to or launched.
## event: Browser.disconnected ## event: Browser.disconnected
@ -32,7 +28,7 @@ Emitted when Browser gets disconnected from the browser application. This might
In case this browser is obtained using [`method: BrowserType.launch`], closes the browser and all of its pages (if any In case this browser is obtained using [`method: BrowserType.launch`], closes the browser and all of its pages (if any
were opened). were opened).
In case this browser is obtained using [`method: BrowserType.connect`], clears all created contexts belonging to this In case this browser is connected to, clears all created contexts belonging to this
browser and disconnects from the browser server. browser and disconnects from the browser server.
The [Browser] object itself is considered to be disposed and cannot be used anymore. The [Browser] object itself is considered to be disposed and cannot be used anymore.

Просмотреть файл

@ -95,6 +95,7 @@ await browserContext.addInitScript({
[`method: Page.addInitScript`] is not defined. [`method: Page.addInitScript`] is not defined.
### param: BrowserContext.addInitScript.script ### param: BrowserContext.addInitScript.script
* langs: js
- `script` <[function]|[string]|[Object]> - `script` <[function]|[string]|[Object]>
- `path` <[path]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional. - `path` <[path]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
- `content` <[string]> Raw script content. Optional. - `content` <[string]> Raw script content. Optional.
@ -102,6 +103,7 @@ await browserContext.addInitScript({
Script to be evaluated in all pages in the browser context. Script to be evaluated in all pages in the browser context.
### param: BrowserContext.addInitScript.arg ### param: BrowserContext.addInitScript.arg
* langs: js
- `arg` <[Serializable]> - `arg` <[Serializable]>
Optional argument to pass to [`param: script`] (only supported when passing a function). Optional argument to pass to [`param: script`] (only supported when passing a function).

Просмотреть файл

@ -1,4 +1,5 @@
# class: BrowserServer # class: BrowserServer
* langs: js
## event: BrowserServer.close ## event: BrowserServer.close

Просмотреть файл

@ -16,6 +16,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
``` ```
## async method: BrowserType.connect ## async method: BrowserType.connect
* langs: js
- returns: <[Browser]> - returns: <[Browser]>
This methods attaches Playwright to an existing browser instance. This methods attaches Playwright to an existing browser instance.
@ -129,6 +130,7 @@ Close the browser process on SIGTERM. Defaults to `true`.
Close the browser process on SIGHUP. Defaults to `true`. Close the browser process on SIGHUP. Defaults to `true`.
### option: BrowserType.launch.logger ### option: BrowserType.launch.logger
* langs: js
- `logger` <[Logger]> - `logger` <[Logger]>
Logger sink for Playwright logging. Logger sink for Playwright logging.
@ -258,6 +260,7 @@ Defaults to 0.
### option: BrowserType.launchPersistentContext.-inline- = %%-shared-context-params-list-%% ### option: BrowserType.launchPersistentContext.-inline- = %%-shared-context-params-list-%%
## async method: BrowserType.launchServer ## async method: BrowserType.launchServer
* langs: js
- returns: <[BrowserServer]> - returns: <[BrowserServer]>
Returns the browser app instance. Returns the browser app instance.
@ -352,6 +355,7 @@ Close the browser process on SIGTERM. Defaults to `true`.
Close the browser process on SIGHUP. Defaults to `true`. Close the browser process on SIGHUP. Defaults to `true`.
### option: BrowserType.launchServer.logger ### option: BrowserType.launchServer.logger
* langs: js
- `logger` <[Logger]> - `logger` <[Logger]>
Logger sink for Playwright logging. Logger sink for Playwright logging.

Просмотреть файл

@ -1,5 +1,6 @@
# class: ChromiumBrowser # class: ChromiumBrowser
* extends: [Browser] * extends: [Browser]
* langs: js
Chromium-specific features including Tracing, service worker support, etc. You can use [`method: Chromium-specific features including Tracing, service worker support, etc. You can use [`method:
ChromiumBrowser.startTracing`] and [`method: ChromiumBrowser.stopTracing`] to create a trace file which can be ChromiumBrowser.startTracing`] and [`method: ChromiumBrowser.stopTracing`] to create a trace file which can be

Просмотреть файл

@ -1,4 +1,5 @@
# class: ChromiumCoverage # class: ChromiumCoverage
* langs: js
Coverage gathers information about parts of JavaScript and CSS that were used by the page. Coverage gathers information about parts of JavaScript and CSS that were used by the page.

Просмотреть файл

@ -22,6 +22,7 @@ downloaded content. If `acceptDownloads` is not set or set to `false`, download
download is not performed and user has no access to the downloaded files. download is not performed and user has no access to the downloaded files.
## async method: Download.createReadStream ## async method: Download.createReadStream
* langs: js
- returns: <[null]|[Readable]> - returns: <[null]|[Readable]>
Returns readable stream for current download or `null` if download failed. Returns readable stream for current download or `null` if download failed.

Просмотреть файл

@ -424,18 +424,8 @@ handle.selectOption('red', 'green', 'blue');
handle.selectOption({ value: 'blue' }, { index: 2 }, 'red'); handle.selectOption({ value: 'blue' }, { index: 2 }, 'red');
``` ```
### param: ElementHandle.selectOption.values ### param: ElementHandle.selectOption.values = %%-select-options-values-%%
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>>
- `value` <[string]> Matches by `option.value`. Optional.
- `label` <[string]> Matches by `option.label`. Optional.
- `index` <[int]> Matches by the index. Optional.
Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option
is considered matching if all specified properties match.
### option: ElementHandle.selectOption.noWaitAfter = %%-input-no-wait-after-%% ### option: ElementHandle.selectOption.noWaitAfter = %%-input-no-wait-after-%%
### option: ElementHandle.selectOption.timeout = %%-input-timeout-%% ### option: ElementHandle.selectOption.timeout = %%-input-timeout-%%
## async method: ElementHandle.selectText ## async method: ElementHandle.selectText

Просмотреть файл

@ -583,19 +583,8 @@ frame.selectOption('select#colors', 'red', 'green', 'blue');
``` ```
### param: Frame.selectOption.selector = %%-query-selector-%% ### param: Frame.selectOption.selector = %%-query-selector-%%
### param: Frame.selectOption.values = %%-select-options-values-%%
### param: Frame.selectOption.values
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>>
- `value` <[string]> Matches by `option.value`. Optional.
- `label` <[string]> Matches by `option.label`. Optional.
- `index` <[int]> Matches by the index. Optional.
Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option
is considered matching if all specified properties match.
### option: Frame.selectOption.noWaitAfter = %%-input-no-wait-after-%% ### option: Frame.selectOption.noWaitAfter = %%-input-no-wait-after-%%
### option: Frame.selectOption.timeout = %%-input-timeout-%% ### option: Frame.selectOption.timeout = %%-input-timeout-%%
## async method: Frame.setContent ## async method: Frame.setContent

Просмотреть файл

@ -1,4 +1,5 @@
# class: Logger # class: Logger
* langs: js
Playwright generates a lot of logs and they are accessible via the pluggable logger sink. Playwright generates a lot of logs and they are accessible via the pluggable logger sink.

Просмотреть файл

@ -315,6 +315,7 @@ await page.addInitScript(preloadFile);
[`method: Page.addInitScript`] is not defined. [`method: Page.addInitScript`] is not defined.
### param: Page.addInitScript.script ### param: Page.addInitScript.script
* langs: js
- `script` <[function]|[string]|[Object]> - `script` <[function]|[string]|[Object]>
- `path` <[path]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional. - `path` <[path]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
- `content` <[string]> Raw script content. Optional. - `content` <[string]> Raw script content. Optional.
@ -322,6 +323,7 @@ await page.addInitScript(preloadFile);
Script to be evaluated in the page. Script to be evaluated in the page.
### param: Page.addInitScript.arg ### param: Page.addInitScript.arg
* langs: js
- `arg` <[Serializable]> - `arg` <[Serializable]>
Optional argument to pass to [`param: script`] (only supported when passing a function). Optional argument to pass to [`param: script`] (only supported when passing a function).
@ -443,6 +445,7 @@ Gets the full HTML contents of the page, including the doctype.
Get the browser context that the page belongs to. Get the browser context that the page belongs to.
## property: Page.coverage ## property: Page.coverage
* langs: js
- type: <[null]|[ChromiumCoverage]> - type: <[null]|[ChromiumCoverage]>
Browser-specific Coverage implementation, only available for Chromium atm. See Browser-specific Coverage implementation, only available for Chromium atm. See
@ -1285,19 +1288,8 @@ page.selectOption('select#colors', ['red', 'green', 'blue']);
Shortcut for main frame's [`method: Frame.selectOption`] Shortcut for main frame's [`method: Frame.selectOption`]
### param: Page.selectOption.selector = %%-input-selector-%% ### param: Page.selectOption.selector = %%-input-selector-%%
### param: Page.selectOption.values = %%-select-options-values-%%
### param: Page.selectOption.values
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>>
- `value` <[string]> Matches by `option.value`. Optional.
- `label` <[string]> Matches by `option.label`. Optional.
- `index` <[int]> Matches by the index. Optional.
Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option
is considered matching if all specified properties match.
### option: Page.selectOption.noWaitAfter = %%-input-no-wait-after-%% ### option: Page.selectOption.noWaitAfter = %%-input-no-wait-after-%%
### option: Page.selectOption.timeout = %%-input-timeout-%% ### option: Page.selectOption.timeout = %%-input-timeout-%%
## async method: Page.setContent ## async method: Page.setContent

Просмотреть файл

@ -43,6 +43,7 @@ const iPhone = devices['iPhone 6'];
``` ```
## property: Playwright.errors ## property: Playwright.errors
* langs: js
- type: <[Object]> - type: <[Object]>
- `TimeoutError` <[function]> A class of [TimeoutError]. - `TimeoutError` <[function]> A class of [TimeoutError].

Просмотреть файл

@ -1,18 +0,0 @@
## async method: Playwright.stop
* langs: python
Terminates this instance of Playwright in case it was created bypassing the Python context manager. This is useful in REPL applications.
```py
>>> from playwright import sync_playwright
>>> playwright = sync_playwright().start()
>>> browser = playwright.chromium.launch()
>>> page = browser.newPage()
>>> page.goto("http://whatsmyuseragent.org/")
>>> page.screenshot(path="example.png")
>>> browser.close()
>>> playwright.stop()
```

Просмотреть файл

@ -215,6 +215,7 @@ Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`
[`method: Page.emulateMedia`] for more details. Defaults to '`light`'. [`method: Page.emulateMedia`] for more details. Defaults to '`light`'.
## context-option-logger ## context-option-logger
* langs: js
- `logger` <[Logger]> - `logger` <[Logger]>
Logger sink for Playwright logging. Logger sink for Playwright logging.
@ -265,6 +266,44 @@ Network proxy settings to use with this context. Note that browser needs to be l
option to work. If all contexts override the proxy, global proxy will be never used and can be any string, for example option to work. If all contexts override the proxy, global proxy will be never used and can be any string, for example
`launch({ proxy: { server: 'per-context' } })`. `launch({ proxy: { server: 'per-context' } })`.
## select-options-values
* langs: js
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>>
- `value` <[string]> Matches by `option.value`. Optional.
- `label` <[string]> Matches by `option.label`. Optional.
- `index` <[int]> Matches by the index. Optional.
Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option
is considered matching if all specified properties match.
## python-select-options-element
* langs: python
- `element` <[ElementHandle]|[Array]<[ElementHandle]>>
Option elements to select. Optional.
## python-select-options-index
* langs: python
- `index` <[int]|[Array]<[int]>>
Options to select by index. Optional.
## python-select-options-value
* langs: python
- `value` <[string]|[Array]<[string]>>
Options to select by value. If the `<select>` has the `multiple` attribute, all given options are selected, otherwise
only the first option matching one of the passed options is selected. Optional.
## python-select-options-label
* langs: python
- `label` <[string]|[Array]<[string]>>
Options to select by label. If the `<select>` has the `multiple` attribute, all given options are selected, otherwise
only the first option matching one of the passed options is selected. Optional.
## shared-context-params-list ## shared-context-params-list
- %%-context-option-acceptdownloads-%% - %%-context-option-acceptdownloads-%%
- %%-context-option-ignorehttpserrors-%% - %%-context-option-ignorehttpserrors-%%

58
docs/src/api/python.md Normal file
Просмотреть файл

@ -0,0 +1,58 @@
## async method: Playwright.stop
* langs: python
Terminates this instance of Playwright in case it was created bypassing the Python context manager. This is useful in REPL applications.
```py
>>> from playwright import sync_playwright
>>> playwright = sync_playwright().start()
>>> browser = playwright.chromium.launch()
>>> page = browser.newPage()
>>> page.goto("http://whatsmyuseragent.org/")
>>> page.screenshot(path="example.png")
>>> browser.close()
>>> playwright.stop()
```
### param: BrowserContext.addInitScript.path
* langs: python
- `path` <[path]>
Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
### param: BrowserContext.addInitScript.script
* langs: python
- `script` <[string]>
Script to be evaluated in all pages in the browser context. Optional.
### param: Page.addInitScript.path
* langs: python
- `path` <[path]>
Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
### param: Page.addInitScript.script
* langs: python
- `script` <[string]>
Script to be evaluated in all pages in the browser context. Optional.
### param: ElementHandle.selectOption.element = %%-python-select-options-element-%%
### param: ElementHandle.selectOption.index = %%-python-select-options-index-%%
### param: ElementHandle.selectOption.value = %%-python-select-options-value-%%
### param: ElementHandle.selectOption.label = %%-python-select-options-label-%%
### param: Frame.selectOption.element = %%-python-select-options-element-%%
### param: Frame.selectOption.index = %%-python-select-options-index-%%
### param: Frame.selectOption.value = %%-python-select-options-value-%%
### param: Frame.selectOption.label = %%-python-select-options-label-%%
### param: Page.selectOption.element = %%-python-select-options-element-%%
### param: Page.selectOption.index = %%-python-select-options-index-%%
### param: Page.selectOption.value = %%-python-select-options-value-%%
### param: Page.selectOption.label = %%-python-select-options-label-%%

18
types/types.d.ts поставляемый
Просмотреть файл

@ -6884,11 +6884,9 @@ export {};
/** /**
* - extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) * - extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
* *
* A Browser is created when Playwright connects to a browser instance, either through * A Browser is created via
* [browserType.launch()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypelaunch) or * [browserType.launch()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypelaunch). An example
* [browserType.connect()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypeconnect). * of using a [Browser] to create a [Page]:
*
* An example of using a [Browser] to create a [Page]:
* *
* ```js * ```js
* const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'. * const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@ -6902,9 +6900,8 @@ export {};
* ``` * ```
* *
* See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that * See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that
* [browserType.connect()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypeconnect) and * [browserType.launch()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypelaunch) always
* [browserType.launch()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypelaunch) always return * returns a specific browser instance, based on the browser being launched.
* a specific browser instance, based on the browser being connected to or launched.
*/ */
export interface Browser extends EventEmitter { export interface Browser extends EventEmitter {
/** /**
@ -6952,9 +6949,8 @@ export interface Browser extends EventEmitter {
* [browserType.launch()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypelaunch), closes the * [browserType.launch()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypelaunch), closes the
* browser and all of its pages (if any were opened). * browser and all of its pages (if any were opened).
* *
* In case this browser is obtained using * In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the
* [browserType.connect()](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypeconnect), clears all * browser server.
* created contexts belonging to this browser and disconnects from the browser server.
* *
* The [Browser] object itself is considered to be disposed and cannot be used anymore. * The [Browser] object itself is considered to be disposed and cannot be used anymore.
*/ */

Просмотреть файл

@ -31,10 +31,10 @@ class ApiParser {
let bodyParts = []; let bodyParts = [];
let paramsPath; let paramsPath;
for (const name of fs.readdirSync(apiDir)) { for (const name of fs.readdirSync(apiDir)) {
if (name.startsWith('class-'))
bodyParts.push(fs.readFileSync(path.join(apiDir, name)).toString());
if (name === 'params.md') if (name === 'params.md')
paramsPath = path.join(apiDir, name); paramsPath = path.join(apiDir, name);
else
bodyParts.push(fs.readFileSync(path.join(apiDir, name)).toString());
} }
const body = md.parse(bodyParts.join('\n')); const body = md.parse(bodyParts.join('\n'));
const params = paramsPath ? md.parse(fs.readFileSync(paramsPath).toString()) : null; const params = paramsPath ? md.parse(fs.readFileSync(paramsPath).toString()) : null;
@ -58,21 +58,16 @@ class ApiParser {
*/ */
parseClass(node) { parseClass(node) {
let extendsName = null; let extendsName = null;
let langs = null;
const name = node.text.substring('class: '.length); const name = node.text.substring('class: '.length);
for (const member of node.children) { for (const member of node.children) {
if (member.type.startsWith('h')) if (member.type.startsWith('h'))
continue; continue;
if (member.type === 'li' && member.text.startsWith('extends: [')) { if (member.type === 'li' && member.liType === 'bullet' && member.text.startsWith('extends: [')) {
extendsName = member.text.substring('extends: ['.length, member.text.indexOf(']')); extendsName = member.text.substring('extends: ['.length, member.text.indexOf(']'));
continue; continue;
} }
if (member.type === 'li' && member.text.startsWith('langs: ')) {
langs = new Set(member.text.substring('langs: '.length).split(',').map(l => l.trim()));
continue;
}
} }
const clazz = new Documentation.Class(langs, name, [], extendsName, extractComments(node)); const clazz = new Documentation.Class(extractLangs(node), name, [], extendsName, extractComments(node));
this.classes.set(clazz.name, clazz); this.classes.set(clazz.name, clazz);
} }
@ -84,13 +79,9 @@ class ApiParser {
const match = spec.text.match(/(event|method|property|async method): ([^.]+)\.(.*)/); const match = spec.text.match(/(event|method|property|async method): ([^.]+)\.(.*)/);
const name = match[3]; const name = match[3];
let returnType = null; let returnType = null;
let langs = null;
for (const item of spec.children || []) { for (const item of spec.children || []) {
if (item.type === 'li' && item.liType === 'default') if (item.type === 'li' && item.liType === 'default')
returnType = this.parseType(item); returnType = this.parseType(item);
if (item.type === 'li' && item.liType === 'bullet' && item.text.startsWith('langs: '))
langs = new Set(item.text.substring('langs: '.length).split(',').map(l => l.trim()));
} }
if (!returnType) if (!returnType)
returnType = new Documentation.Type('void'); returnType = new Documentation.Type('void');
@ -103,11 +94,11 @@ class ApiParser {
let member; let member;
if (match[1] === 'event') if (match[1] === 'event')
member = Documentation.Member.createEvent(langs, name, returnType, extractComments(spec)); member = Documentation.Member.createEvent(extractLangs(spec), name, returnType, extractComments(spec));
if (match[1] === 'property') if (match[1] === 'property')
member = Documentation.Member.createProperty(langs, name, returnType, extractComments(spec)); member = Documentation.Member.createProperty(extractLangs(spec), name, returnType, extractComments(spec));
if (match[1] === 'method' || match[1] === 'async method') if (match[1] === 'method' || match[1] === 'async method')
member = Documentation.Member.createMethod(langs, name, [], returnType, extractComments(spec)); member = Documentation.Member.createMethod(extractLangs(spec), name, [], returnType, extractComments(spec));
const clazz = this.classes.get(match[2]); const clazz = this.classes.get(match[2]);
clazz.membersArray.push(member); clazz.membersArray.push(member);
} }
@ -138,11 +129,11 @@ class ApiParser {
* @param {MarkdownNode} spec * @param {MarkdownNode} spec
*/ */
parseProperty(spec) { parseProperty(spec) {
const param = spec.children[0]; const param = childrenWithoutProperties(spec)[0];
const text = param.text; const text = param.text;
const name = text.substring(0, text.indexOf('<')).replace(/\`/g, '').trim(); const name = text.substring(0, text.indexOf('<')).replace(/\`/g, '').trim();
const comments = extractComments(spec); const comments = extractComments(spec);
return Documentation.Member.createProperty(null, name, this.parseType(param), comments, guessRequired(md.render(comments))); return Documentation.Member.createProperty(extractLangs(spec), name, this.parseType(param), comments, guessRequired(md.render(comments)));
} }
/** /**
@ -150,10 +141,10 @@ class ApiParser {
* @return {Documentation.Type} * @return {Documentation.Type}
*/ */
parseType(spec) { parseType(spec) {
const arg = parseArgument(spec.text); const arg = parseVariable(spec.text);
const properties = []; const properties = [];
for (const child of spec.children || []) { for (const child of spec.children || []) {
const { name, text } = parseArgument(child.text); const { name, text } = parseVariable(child.text);
const comments = /** @type {MarkdownNode[]} */ ([{ type: 'text', text }]); const comments = /** @type {MarkdownNode[]} */ ([{ type: 'text', text }]);
properties.push(Documentation.Member.createProperty(null, name, this.parseType(child), comments, guessRequired(text))); properties.push(Documentation.Member.createProperty(null, name, this.parseType(child), comments, guessRequired(text)));
} }
@ -165,7 +156,7 @@ class ApiParser {
* @param {string} line * @param {string} line
* @returns {{ name: string, type: string, text: string }} * @returns {{ name: string, type: string, text: string }}
*/ */
function parseArgument(line) { function parseVariable(line) {
let match = line.match(/^`([^`]+)` (.*)/); let match = line.match(/^`([^`]+)` (.*)/);
if (!match) if (!match)
match = line.match(/^(returns): (.*)/); match = line.match(/^(returns): (.*)/);
@ -209,7 +200,8 @@ function applyTemplates(body, params) {
const template = paramsMap.get(prop.text); const template = paramsMap.get(prop.text);
if (!template) if (!template)
throw new Error('Bad template: ' + prop.text); throw new Error('Bad template: ' + prop.text);
const { name: argName } = parseArgument(template.children[0].text); const children = childrenWithoutProperties(template);
const { name: argName } = parseVariable(children[0].text);
parent.children.push({ parent.children.push({
type: node.type, type: node.type,
text: name + argName, text: name + argName,
@ -281,4 +273,23 @@ function parseApi(apiDir) {
return new ApiParser(apiDir).documentation; return new ApiParser(apiDir).documentation;
} }
/**
* @param {MarkdownNode} spec
* @returns {?Set<string>}
*/
function extractLangs(spec) {
for (const child of spec.children)
if (child.type === 'li' && child.liType === 'bullet' && child.text.startsWith('langs: '))
return new Set(child.text.substring('langs: '.length).split(',').map(l => l.trim()));
return null;
}
/**
* @param {MarkdownNode} spec
* @returns {MarkdownNode[]}
*/
function childrenWithoutProperties(spec) {
return spec.children.filter(c => c.liType !== 'bullet' || !c.text.startsWith('langs'));
}
module.exports = { parseApi }; module.exports = { parseApi };

Просмотреть файл

@ -88,6 +88,7 @@ function sanitize(result) {
delete result.args; delete result.args;
delete result.argsArray; delete result.argsArray;
delete result.clazz; delete result.clazz;
delete result.langs;
delete result.spec; delete result.spec;
} }