diff --git a/README.md b/README.md index c73d3b9af8b3bea1d7c352ddbd019751373defca..93343d0b89da653651474700d647c375f676fa55 100755 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ The interface of URL is used to parse, construct, normalize, and encode URLs. Th URI Represents a Uniform Resource Identifier (URI) reference. -XML representation refers to extensible markup language。 +XML representation refers to extensible markup language. ## Contents @@ -36,7 +36,7 @@ base/compileruntime/js_api_module/ │ ├── username # username attribute │ ├── toString() # toString method │ └── toJSON() # toJSON method -├── Class: URLSearchParams # URLSearchParams class +├── Class: URLSearchParams # URLSearchParams class │ ├── new URLSearchParams() # Create URLSearchParams object │ ├── new URLSearchParams(string) # Create URLSearchParams object │ ├── new URLSearchParams(obj) # Create URLSearchParams object @@ -54,9 +54,9 @@ base/compileruntime/js_api_module/ │ ├── toString() # toString method │ ├── values() # values method │ └── urlSearchParams[Symbol.iterator]() # Create URLSearchParams object -├── Class:URI # URI class -│ ├── URI​(String str) # URI class -│ ├── scheme # Create URI object +├── Class:URI # URI class +│ ├── URI(String str) # URI class +│ ├── scheme # Create URI object │ ├── authority # scheme attribute │ ├── ssp # authority attribute │ ├── userinfo # ssp attribute @@ -66,13 +66,13 @@ base/compileruntime/js_api_module/ │ ├── fragment # query attribute │ ├── path # fragment attribute │ ├── equals(Object ob) # path method -│ ├── normalize​() # equals method -│ ├── isAbsolute​() # normalize method -│ ├── normalize​() # isAbsolute method +│ ├── normalize() # equals method +│ ├── isAbsolute() # normalize method +│ ├── normalize() # isAbsolute method │ └── toString() # normalize method -└── Class:ConvertXml # ConvertXml class - ├── ConvertXml() # Create convertxml class object - └── convert(String xml, Object options) # Convert method +└── Class:ConvertXml # ConvertXml class + ├── ConvertXml() # Create convertxml class object + └── convert(String xml, Object options) # Convert method ``` ## Illustrate @@ -80,10 +80,9 @@ base/compileruntime/js_api_module/ ### Interface Description -| Interface name | Illustrate | +| Interface name | Illustrate | | -------- | -------- | -//URL -| new URL(url: string,base?:string I URL) | Create and return a URL object that references the URL specified by the absolute URL string, the relative URL string, and the basic URL string. | +| new URL(url: string,base?:string \| URL) | Create and return a URL object that references the URL specified by the absolute URL string, the relative URL string, and the basic URL string. | | tostring():string | The stringification method returns a USVString containing the complete URL. It is equivalent to the read-only URL.href. | | toJSON():string | This method returns a USVString, which contains a serialized URL version. | | new URLSearchParams() | The URLSearchParams() constructor has no parameters. This method creates and returns a new URLSearchParams object. The beginning'?' character will be ignored. | @@ -94,18 +93,17 @@ base/compileruntime/js_api_module/ | set(name: string, value string): void | Retrieve whether the searchParams object contains a key-value pair whose key is name. If not, add the key-value pair, if any, modify the value corresponding to the first key in the object, and delete the remaining key-value pairs whose key is name. | | sort(): void | According to the Unicode code point of the key, sort all key/value pairs contained in this object and return undefined. | | toString(): string | According to the searchParams object, the query string applicable in the URL is returned. | -| keys(): iterableIterator | Return an iterator, which allows iterating through all the key values contained in the object. | -| values(): iterableIterator | Returns an iterator, which allows iterating over all the value values contained in the object. | +| keys(): iterableIterator\ | Return an iterator, which allows iterating through all the key values contained in the object. | +| values(): iterableIterator\ | Returns an iterator, which allows iterating over all the value values contained in the object. | | append(name: string, value: string): void | Insert the name, value key-value pair in the searchParams object. | | delete(name: string): void | Traverse the searchParams object, find all the names, and delete the corresponding key-value pairs. | | get(name: string): string | Retrieve the first name in the searchParams object and return the value corresponding to the name key. | | getAll(name: string): string[] | Retrieve all names in the searchParams object and return all the values corresponding to the name key. | | entries(): iterableIterator<[string, string]> | Returns an iterator that allows iterating through all key/value pairs contained in the searchParams object. | | forEach(): void | Through the callback function to traverse the key-value pairs on the URLSearchParams instance object. | -| urlSearchParams[Symbol.iterator] () | Returns an ES6 iterator for each name-value pair in the query string. Each item of the iterator is a JavaScript array. | -//URI +| urlSearchParams\[Symbol.iterator]() | Returns an ES6 iterator for each name-value pair in the query string. Each item of the iterator is a JavaScript array. | | URI​(String str) | Construct the URI by parsing the given input parameter (String str). This constructor parses the given string strictly in accordance with the grammatical provisions in RFC 2396 Appendix A. | -| getScheme​() | Return the scheme component of this URI, or null if the scheme is not defined | +| getScheme​() | Return the scheme component of this URI, or null if the scheme is not defined. | | getAuthority​() | Returns the decoded authority component of this URI, or null if authority is not defined. The string returned by this method is the same as the string returned by the getRawAuthority method, except that all escaped octet sequences are decoded. | | getSchemeSpecificPart​() | Returns the decoding scheme-specific part of this URI. The string returned by this method is the same as the string returned by the getRawSchemeSpecificPart method, except that all escaped octet sequences are decoded. | | getUserInfo​() | Returns the decoded userinfo component of this URI. The userinfo component of the URI (if defined) only contains characters in unreserved, punctuation, escape, and other categories. | @@ -118,7 +116,6 @@ base/compileruntime/js_api_module/ | normalize​() | Normalize the path of this URI. If this URI is opaque, or its path is already in normal form, then this URI is returned. Otherwise, a new URI identical to this URI will be constructed. | | isAbsolute​() | Determine whether this URI is absolute. If and only if it has a scheme component, the URI is absolute and the return value is true, otherwise the return value is false. | | toString() | Return the content of this URI as a string. | -//ConvertXml | ConvertXml() | The constructor used to construct the convertxml class object. This constructor does not need to pass in parameters. | | convert(String xml, Object options) | Returns a JavaScript object that converts an XML string as required by the option. | @@ -126,8 +123,6 @@ base/compileruntime/js_api_module/ The usage of each interface is as follows: -1.URL - 1、new URL(url: string,base?:string|URL) ``` let b = new URL('https://developer.mozilla.org'); // => 'https://developer.mozilla.org/' @@ -173,7 +168,6 @@ console.log(params.getAll('query')); 7、new URLSearchParams(iterable) ``` let params; - // Using an array params = new URLSearchParams([ ['user', 'abc'], @@ -199,13 +193,13 @@ params .sort(); ``` console.log(params .toString()); // =>bar=2&baz=3&foo=1' ``` -12、keys(): iterableIterator +12、keys(): iterableIterator\ ``` for(var key of params.keys()) { console.log(key); } // =>bar baz foo ``` -13、values(): iterableIterator +13、values(): iterableIterator\ ``` for(var value of params.values()) { console.log(value); @@ -252,93 +246,89 @@ for (const [name, value] of params) { // xyz ba ``` -2.URI - -1、URI​(String str) +21、URI​(String str) ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); ``` -2、scheme +22、scheme ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.scheme // => "http"; ``` -3、authority +23、authority ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.authority // => "gg:gaogao@www.baidu.com:99"; ``` -4、ssp +24、ssp ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.ssp " // => gg:gaogao@www.baidu.com:99/path/path?query"; ``` -5、userinfo +25、userinfo ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.userinfo // => "gg:gaogao"; ``` -6、host +26、host ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.host // => "www.baidu.com"; ``` -7、port +27、port ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.port // => "99"; ``` -8、query +28、query ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.query // => "query"; ``` -9、fragment +29、fragment ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.fragment // => "fagment"; ``` -10、path +30、path ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.path // => "/path/path"; ``` -11、equals(Object ob) +31、equals(Object ob) ``` let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path1?query#fagment'); let gaogao1 = gaogao; let res = gaogao.equals(gaogao1); console.log(res); // => true; ``` -12、normalize​() +32、normalize​() ``` let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/66./../././mm/.././path1?query#fagment'); let res = gaogao.normalize(); console.log(res.path); // => "/path/path1" console.log(res.toString()); // => "http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/path1?query#fagment" ``` -13、isAbsolute​() +33、isAbsolute​() ``` let gaogao = new Uri.URI('f/tp://username:password@www.baidu.com:88/path?query#fagment'); let res = gaogao.isAbsolute(); console.log(res); //=> false; ``` -14、toString() +34、toString() ``` let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'); let res = gaogao.toString(); console.log(res.toString()); // => 'http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'; ``` - -3.ConvertXml - -1、ConvertXml() +35、ConvertXml() ``` var convertml = new convertXml.ConvertXml(); ``` -2、convert(String xml, Object options) +36、convert(String xml, Object options) ``` var result = convertml.convert(xml, {compact: false, spaces: 4}); +``` ## Related warehouse [js_api_module Subsystem](https://gitee.com/OHOS_STD/js_api_module) diff --git a/README_zh.md b/README_zh.md index 21b80b580906ace8a5fb7f8c649d57a77fdd4740..794dbbd9c803ec393de0da531e0b5ed72a8e15a4 100755 --- a/README_zh.md +++ b/README_zh.md @@ -36,7 +36,7 @@ base/compileruntime/js_api_module/ │ ├── username # username属性 │ ├── toString() # toString方法 │ └── toJSON() # toJSON方法 -├── Class: URLSearchParams # URLSearchParams类 +├── Class: URLSearchParams # URLSearchParams类 │ ├── new URLSearchParams() # 创建URLSearchParams对象 │ ├── new URLSearchParams(string) # 创建URLSearchParams对象 │ ├── new URLSearchParams(obj) # 创建URLSearchParams对象 @@ -54,8 +54,8 @@ base/compileruntime/js_api_module/ │ ├── toString() # toString方法 │ ├── values() # values方法 │ └── urlSearchParams[Symbol.iterator]() # 创建URLSearchParams对象 -├── Class:URI # URI类 -│ ├── URI​(String str) # 创建URI对象 +├── Class:URI # URI类 +│ ├── URI(String str) # 创建URI对象 │ ├── scheme # scheme属性 │ ├── authority # authority属性 │ ├── ssp # ssp属性 @@ -66,13 +66,13 @@ base/compileruntime/js_api_module/ │ ├── fragment # fragment属性 │ ├── path # path属性 │ ├── equals(Object ob) # equals方法 -│ ├── normalize​() # normalize方法 -│ ├── isAbsolute​() # isAbsolute方法 -│ ├── normalize​() # normalize方法 +│ ├── normalize() # normalize方法 +│ ├── isAbsolute() # isAbsolute方法 +│ ├── normalize() # normalize方法 │ └── toString() # toString方法 -└── Class:ConvertXml # ConvertXml类 - ├── ConvertXml() # 创建ConvertXml类对象 - └── convert(String xml, Object options) # convert方法 +└── Class:ConvertXml # ConvertXml类 + ├── ConvertXml() # 创建ConvertXml类对象 + └── convert(String xml, Object options) # convert方法 ``` ## 说明 @@ -80,10 +80,9 @@ base/compileruntime/js_api_module/ ### 接口说明 -| 接口名 | 说明 | +| 接口名 | 说明 | | -------- | -------- | -//URL -| URL(url: string,base?:string I URL) | 创建并返回一个URL对象,该URL对象引用使用绝对URL字符串,相对URL字符串和基本URL字符串指定的URL。 | +| URL(url: string,base?:string \| URL) | 创建并返回一个URL对象,该URL对象引用使用绝对URL字符串,相对URL字符串和基本URL字符串指定的URL。 | | tostring():string | 该字符串化方法返回一个包含完整 URL 的 USVString。它的作用等同于只读的 URL.href。 | | toJSON():string | 该方法返回一个USVString,其中包含一个序列化的URL版本。 | | new URLSearchParams() | URLSearchParams() 构造器无入参,该方法创建并返回一个新的URLSearchParams 对象。 开头的'?' 字符会被忽略。 | @@ -94,17 +93,15 @@ base/compileruntime/js_api_module/ | set(name: string, value string): void | 检索searchParams对象中是否含有key为name的键值对。没有的话则添加该键值对,有的话则修改对象中第一个key所对应的value,并删除键为name的其余键值对。 | | sort(): void | 根据键的Unicode代码点,对包含在此对象中的所有键/值对进行排序,并返回undefined。 | | toString(): string | 根据searchParams对象,返回适用在URL中的查询字符串。 | -| keys(): iterableIterator | 返回一个iterator,遍历器允许遍历对象中包含的所有key值。 | -| values(): iterableIterator | 返回一个iterator,遍历器允许遍历对象中包含的所有value值。 | +| keys(): iterableIterator\ | 返回一个iterator,遍历器允许遍历对象中包含的所有key值。 | +| values(): iterableIterator\ | 返回一个iterator,遍历器允许遍历对象中包含的所有value值。 | | append(name: string, value: string): void | 在searchParams对象中插入name, value键值对。 | | delete(name: string): void | 遍历searchParams对象,查找所有的name,删除对应的键值对。 | | get(name: string): string | 检索searchParams对象中第一个name,返回name键对应的值。 | | getAll(name: string): string[] | 检索searchParams对象中所有name,返回name键对应的所有值。 | | entries(): iterableIterator<[string, string]> | 返回一个iterator,允许遍历searchParams对象中包含的所有键/值对。 | | forEach(): void | 通过回调函数来遍历URLSearchParams实例对象上的键值对。 | -| urlSearchParams[Symbol.iterator] () | 返回查询字符串中每个名称-值对的ES6迭代器。迭代器的每个项都是一个JavaScript数组。 | - -//URI +| urlSearchParams\[Symbol.iterator]() | 返回查询字符串中每个名称-值对的ES6迭代器。迭代器的每个项都是一个JavaScript数组。 | | URI​(String str) | 通过解析给定入参(String str)来构造URI。此构造函数严格按照RFC 2396附录A中的语法规定解析给定字符串。 | | scheme​ | 返回此 URI 的scheme部分,如果scheme未定义,则返回 null | | authority​ | 返回此 URI 的解码authority部分,如果authority未定义,则返回 null。 | @@ -118,8 +115,6 @@ base/compileruntime/js_api_module/ | equals(Object ob) | 测试此 URI 是否与另一个对象相等。如果给定的对象不是 URI,则此方法立即返回 false。 | | normalize​() | 规范化这个 URI 的路径。如果这个 URI 的path不规范,将规范后构造一个新 URI对象返回。 | | isAbsolute​() | 判断这个 URI 是否是绝对的。当且仅当它具有scheme部分时,URI 是绝对的,返回值为true,否则返回值为false。 | - -//ConvertXml | ConvertXml() | 用于构造ConvertXml类对象的构造函数。此构造函数无需传入参数。 | | convert(String xml, Object options) | 返回按选项要求转化xml字符串的JavaScrip对象。 | @@ -127,8 +122,6 @@ base/compileruntime/js_api_module/ 各接口使用方法如下: -1.URL - 1、new URL(url: string,base?:string|URL) ``` let b = new URL('https://developer.mozilla.org'); // => 'https://developer.mozilla.org/' @@ -140,7 +133,7 @@ let a = new URL( 'sca/./path/path/../scasa/text', 'http://www.example.com'); ``` const url = new URL('http://10.0xFF.O400.235:8080/directory/file?query#fragment'); url.toString() // => 'http://10.0xff.o400.235:8080/directory/file?query#fragment' - + const url = new URL("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"); url.toString() // => 'http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/index.html' @@ -200,13 +193,13 @@ params .sort(); ``` console.log(params .toString()); // =>bar=2&baz=3&foo=1' ``` -12、keys(): iterableIterator +12、keys(): iterableIterator\ ``` for(var key of params.keys()) { console.log(key); } // =>bar baz foo ``` -13、values(): iterableIterator +13、values(): iterableIterator\ ``` for(var value of params.values()) { console.log(value); @@ -253,91 +246,87 @@ for (const [name, value] of params) { // xyz ba ``` -2.URI - -1、URI​(String str) +21、URI​(String str) ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); ``` -2、scheme +22、scheme ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.scheme // => "http"; ``` -3、authority +23、authority ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.authority // => "gg:gaogao@www.baidu.com:99"; ``` -4、ssp +24、ssp ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.ssp " // => gg:gaogao@www.baidu.com:99/path/path?query"; ``` -5、userinfo +25、userinfo ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.userinfo // => "gg:gaogao"; ``` -6、host +26、host ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.host // => "www.baidu.com"; ``` -7、port +27、port ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.port // => "99"; ``` -8、query +28、query ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.query // => "query"; ``` -9、fragment +29、fragment ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.fragment // => "fagment"; ``` -10、path +30、path ``` let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); gaogao.path // => "/path/path"; ``` -11、equals(Object ob) +31、equals(Object ob) ``` let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path1?query#fagment'); let gaogao1 = gaogao; let res = gaogao.equals(gaogao1); console.log(res); // => true; ``` -12、normalize​() +32、normalize​() ``` let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/66./../././mm/.././path1?query#fagment'); let res = gaogao.normalize(); console.log(res.path); // => "/path/path1" console.log(res.toString()); // => "http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/path1?query#fagment" ``` -13、isAbsolute​() +33、isAbsolute​() ``` let gaogao = new Uri.URI('f/tp://username:password@www.baidu.com:88/path?query#fagment'); let res = gaogao.isAbsolute(); console.log(res); //=> false; ``` -14、toString() +34、toString() ``` let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'); let res = gaogao.toString(); console.log(res.toString()); // => 'http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'; ``` -3.ConvertXml - -1、ConvertXml() +35、ConvertXml() ``` var convertml = new convertXml.ConvertXml(); ``` -2、convert(String xml, Object options) +36、convert(String xml, Object options) ``` var result = convertml.convert(xml, {compact: false, spaces: 4}); ``` diff --git a/convertxml/BUILD.gn b/convertxml/BUILD.gn index a2ac7c536b7250ae16d2459827d607085065270f..5e130653494a2fda376dbcee36d22e4a765e9b9f 100755 --- a/convertxml/BUILD.gn +++ b/convertxml/BUILD.gn @@ -11,14 +11,58 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") +import("//foundation/ace/ace_engine/ace_config.gni") + +# compile .ts to .js. +action("build_ts_js") { + script = "//base/compileruntime/js_api_module/convertxml/build_ts_js.py" + depfile = "$target_gen_dir/$target_name.d" + outputs = [ target_out_dir + "/js_convertxml.js" ] +} base_output_path = get_label_info(":js_convertxml", "target_out_dir") js_xml_obj_path = base_output_path + "/convertxml.o" gen_js_obj("js_convertxml") { - input = "//base/compileruntime/js_api_module/convertxml/js_convertxml.js" + input = "$target_out_dir/js_convertxml.js" output = js_xml_obj_path + dep = ":build_ts_js" +} + +# compile .js to .abc. +action("gen_convertxml_abc") { + visibility = [ ":*" ] + script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" + + args = [ + "--src-js", + rebase_path(target_out_dir + "/js_convertxml.js"), + "--dst-file", + rebase_path(target_out_dir + "/convertxml.abc"), + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + deps = [ + ":build_ts_js", + "//ark/ts2abc/ts2panda:ark_ts2abc_build", + ] + + inputs = [ target_out_dir + "/js_convertxml.js" ] + outputs = [ target_out_dir + "/convertxml.abc" ] +} + +abc_output_path = get_label_info(":convertxml_abc", "target_out_dir") +convertxml_abc_obj_path = abc_output_path + "/convertxml_abc.o" +gen_js_obj("convertxml_abc") { + input = "$target_out_dir/convertxml.abc" + output = convertxml_abc_obj_path + dep = ":gen_convertxml_abc" } ohos_shared_library("convertxml") { @@ -36,6 +80,7 @@ ohos_shared_library("convertxml") { ] deps = [ + ":convertxml_abc", ":js_convertxml", "//base/compileruntime/js_api_module/convertxml/:js_convertxml", "//foundation/ace/napi/:ace_napi", diff --git a/convertxml/build_ts_js.py b/convertxml/build_ts_js.py new file mode 100755 index 0000000000000000000000000000000000000000..83a660e130acfe632de5f40caf54bf199632ae56 --- /dev/null +++ b/convertxml/build_ts_js.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os + +if __name__ == '__main__': + + build_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir("%s/base/compileruntime/js_api_module/convertxml" % build_path) + os.system('../../../../developtools/ace-ets2bundle/compiler/node_modules/typescript/bin/tsc') + + if os.access("../../../../out/ohos-arm64-release", os.F_OK): + os.system('cp -r ./out/js_convertxml.js ../../../../out/ohos-arm64-release/obj/base/compileruntime/js_api_module/convertxml/js_convertxml.js') + + if os.access("../../../../out/ohos-arm-release", os.F_OK): + os.system('cp -r ./out/js_convertxml.js ../../../../out/ohos-arm-release/obj/base/compileruntime/js_api_module/convertxml/js_convertxml.js') + + os.system('rm -rf ./out') \ No newline at end of file diff --git a/convertxml/js_convertxml.cpp b/convertxml/js_convertxml.cpp index 727565fbfb941d4e75a6feea024641ce787c9ef3..190c2bb89dfa3c30f35eb107725c48b4dd024b4a 100755 --- a/convertxml/js_convertxml.cpp +++ b/convertxml/js_convertxml.cpp @@ -15,427 +15,581 @@ #include "js_convertxml.h" #include "securec.h" #include "utils/log.h" - +namespace OHOS::Xml { ConvertXml::ConvertXml(napi_env env): env_(env) { - m_SpaceType = SpaceType::T_INIT; - m_strSpace = ""; - m_iSpace = 0; -} -std::string ConvertXml::GetNodeType(xmlElementType enumType) -{ - std::string strResult = ""; - switch (enumType) { - case xmlElementType::XML_ELEMENT_NODE: - strResult = "element"; - break; - case xmlElementType::XML_ATTRIBUTE_NODE: - strResult = "attribute"; - break; - case xmlElementType::XML_TEXT_NODE: - strResult = "text"; - break; - case xmlElementType::XML_CDATA_SECTION_NODE: - strResult = "cdata"; - break; - case xmlElementType::XML_ENTITY_REF_NODE: - strResult = "entity_ref"; - break; - case xmlElementType::XML_ENTITY_NODE: - strResult = "entity"; - break; - case xmlElementType::XML_PI_NODE: - strResult = "instruction"; - break; - case xmlElementType::XML_COMMENT_NODE: - strResult = "comment"; - break; - case xmlElementType::XML_DOCUMENT_NODE: - strResult = "document"; - break; - case xmlElementType::XML_DOCUMENT_TYPE_NODE: - strResult = "document_type"; - break; - case xmlElementType::XML_DOCUMENT_FRAG_NODE: - strResult = "document_frag"; - break; - case xmlElementType::XML_DTD_NODE: - strResult = "doctype"; - break; + spaceType_ = SpaceType::T_INIT; + strSpace_ = ""; + iSpace_ = 0; + } + std::string ConvertXml::GetNodeType(const xmlElementType enumType) const + { + std::string strResult = ""; + switch (enumType) { + case xmlElementType::XML_ELEMENT_NODE: + strResult = "element"; + break; + case xmlElementType::XML_ATTRIBUTE_NODE: + strResult = "attribute"; + break; + case xmlElementType::XML_TEXT_NODE: + strResult = "text"; + break; + case xmlElementType::XML_CDATA_SECTION_NODE: + strResult = "cdata"; + break; + case xmlElementType::XML_ENTITY_REF_NODE: + strResult = "entity_ref"; + break; + case xmlElementType::XML_ENTITY_NODE: + strResult = "entity"; + break; + case xmlElementType::XML_PI_NODE: + strResult = "instruction"; + break; + case xmlElementType::XML_COMMENT_NODE: + strResult = "comment"; + break; + case xmlElementType::XML_DOCUMENT_NODE: + strResult = "document"; + break; + case xmlElementType::XML_DOCUMENT_TYPE_NODE: + strResult = "document_type"; + break; + case xmlElementType::XML_DOCUMENT_FRAG_NODE: + strResult = "document_frag"; + break; + case xmlElementType::XML_DTD_NODE: + strResult = "doctype"; + break; #ifdef LIBXML_DOCB_ENABLED - case xmlElementType::XML_DOCB_DOCUMENT_NODE: - strResult = "docb_document"; - break; + case xmlElementType::XML_DOCB_DOCUMENT_NODE: + strResult = "docb_document"; + break; #endif - default: - break; + default: + break; + } + return strResult; } - return strResult; -} -void ConvertXml::SetKeyValue(napi_value &object, std::string strKey, std::string strValue) -{ - napi_value attrValue = nullptr; - napi_create_string_utf8(env_, strValue.c_str(), NAPI_AUTO_LENGTH, &attrValue); - napi_set_named_property(env_, object, strKey.c_str(), attrValue); -} -std::string ConvertXml::Trim(std::string strXmltrim) -{ - if (strXmltrim.empty()) { - return ""; + void ConvertXml::SetKeyValue(const napi_value &object, const std::string strKey, const std::string strValue) const + { + napi_value attrValue = nullptr; + napi_create_string_utf8(env_, strValue.c_str(), NAPI_AUTO_LENGTH, &attrValue); + napi_set_named_property(env_, object, strKey.c_str(), attrValue); } - size_t i = 0; - size_t strlen = strXmltrim.size(); - for (; i < strlen;) { - if (strXmltrim[i] == ' ') { - i++; - } else { - break; + std::string ConvertXml::Trim(std::string strXmltrim) const + { + if (strXmltrim.empty()) { + return ""; } - } - strXmltrim = strXmltrim.substr(i); - strlen = strXmltrim.size(); - for (i = strlen - 1; i != 0; i--) { - if (strXmltrim[i] == ' ') { - strXmltrim.pop_back(); - } else { - break; + size_t i = 0; + size_t strlen = strXmltrim.size(); + for (; i < strlen;) { + if (strXmltrim[i] == ' ') { + i++; + } else { + break; + } + } + strXmltrim = strXmltrim.substr(i); + strlen = strXmltrim.size(); + for (i = strlen - 1; i != 0; i--) { + if (strXmltrim[i] == ' ') { + strXmltrim.pop_back(); + } else { + break; + } } + return strXmltrim; } - return strXmltrim; -} -void ConvertXml::GetPrevNodeList(xmlNodePtr curNode) -{ - while (curNode->prev != nullptr) { - curNode = curNode->prev; - napi_value elementsObject = nullptr; - napi_create_object(env_, &elementsObject); - if (curNode->type == xmlElementType::XML_PI_NODE && !m_Options.ignoreInstruction) { - SetKeyValue(elementsObject, m_Options.type, GetNodeType(curNode->type)); - SetKeyValue(elementsObject, m_Options.name, (char*)curNode->name); - SetKeyValue(elementsObject, m_Options.instruction, (const char*)xmlNodeGetContent(curNode)); - m_prevObj.push_back(elementsObject); - } - if (curNode->type == xmlElementType::XML_COMMENT_NODE && !m_Options.ignoreComment) { - SetKeyValue(elementsObject, m_Options.type, GetNodeType(curNode->type)); - SetKeyValue(elementsObject, m_Options.comment, (const char*)xmlNodeGetContent(curNode)); - m_prevObj.push_back(elementsObject); - } - if (curNode->type == xmlElementType::XML_DTD_NODE && !m_Options.ignoreDoctype) { - SetKeyValue(elementsObject, m_Options.type, GetNodeType(curNode->type)); - SetKeyValue(elementsObject, m_Options.doctype, (char*)curNode->name); - m_prevObj.push_back(elementsObject); + void ConvertXml::GetPrevNodeList(xmlNodePtr curNode) + { + while (curNode->prev != nullptr) { + curNode = curNode->prev; + napi_value elementsObject = nullptr; + napi_create_object(env_, &elementsObject); + if (curNode->type == xmlElementType::XML_PI_NODE && !options_.ignoreInstruction) { + SetKeyValue(elementsObject, options_.type, GetNodeType(curNode->type)); + SetKeyValue(elementsObject, options_.name, reinterpret_cast(curNode->name)); + if (xmlNodeGetContent(curNode) != nullptr) { + SetKeyValue(elementsObject, options_.instruction, + reinterpret_cast(xmlNodeGetContent(curNode))); + } + prevObj_.push_back(elementsObject); + } + if (curNode->type == xmlElementType::XML_COMMENT_NODE && !options_.ignoreComment) { + SetKeyValue(elementsObject, options_.type, GetNodeType(curNode->type)); + if (xmlNodeGetContent(curNode) != nullptr) { + SetKeyValue(elementsObject, options_.comment, + reinterpret_cast(xmlNodeGetContent(curNode))); + } + prevObj_.push_back(elementsObject); + } + if (curNode->type == xmlElementType::XML_DTD_NODE && !options_.ignoreDoctype) { + SetKeyValue(elementsObject, options_.type, GetNodeType(curNode->type)); + SetKeyValue(elementsObject, options_.doctype, + reinterpret_cast(curNode->name)); + prevObj_.push_back(elementsObject); + } } } -} -void ConvertXml::SetAttributes(xmlNodePtr curNode, napi_value &elementsObject) -{ - xmlAttr *attr = curNode->properties; - if (attr && !m_Options.ignoreAttributes) { - napi_value attrTitleObj = nullptr; - napi_create_object(env_, &attrTitleObj); - while (attr) { - SetKeyValue(attrTitleObj, (const char*)attr->name, (const char*)attr->children->content); - attr = attr->next; - } - napi_set_named_property(env_, elementsObject, m_Options.attributes.c_str(), attrTitleObj); + void ConvertXml::SetAttributes(xmlNodePtr curNode, const napi_value &elementsObject) const + { + xmlAttr *attr = curNode->properties; + if (attr && !options_.ignoreAttributes) { + napi_value attrTitleObj = nullptr; + napi_create_object(env_, &attrTitleObj); + while (attr) { + SetKeyValue(attrTitleObj, reinterpret_cast(attr->name), + reinterpret_cast(attr->children->content)); + attr = attr->next; + } + napi_set_named_property(env_, elementsObject, options_.attributes.c_str(), attrTitleObj); + } } -} -void ConvertXml::SetXmlElementType(xmlNodePtr curNode, napi_value &elementsObject, bool &bFlag) -{ - if (curNode->type == xmlElementType::XML_PI_NODE && !m_Options.ignoreInstruction) { - SetKeyValue(elementsObject, m_Options.instruction.c_str(), (const char*)xmlNodeGetContent(curNode)); - bFlag = true; - } else if (curNode->type == xmlElementType::XML_COMMENT_NODE && !m_Options.ignoreComment) { - SetKeyValue(elementsObject, m_Options.comment.c_str(), (const char*)xmlNodeGetContent(curNode)); - bFlag = true; - } else if (curNode->type == xmlElementType::XML_CDATA_SECTION_NODE && !m_Options.ignoreCdata) { - SetKeyValue(elementsObject, m_Options.cdata, (const char*)xmlNodeGetContent(curNode)); - bFlag = true; - } -} -void ConvertXml::SetNodeInfo(xmlNodePtr curNode, napi_value &elementsObject) -{ - if (curNode->type == xmlElementType::XML_PI_NODE) { - if (!m_Options.ignoreInstruction) { - SetKeyValue(elementsObject, m_Options.type, GetNodeType(curNode->type)); + void ConvertXml::SetXmlElementType(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const + { + if (curNode->type == xmlElementType::XML_PI_NODE && !options_.ignoreInstruction) { + if (xmlNodeGetContent(curNode) != nullptr) { + SetKeyValue(elementsObject, options_.instruction.c_str(), + reinterpret_cast(xmlNodeGetContent(curNode))); + bFlag = true; + } + } else if (curNode->type == xmlElementType::XML_COMMENT_NODE && !options_.ignoreComment) { + if (xmlNodeGetContent(curNode) != nullptr) { + SetKeyValue(elementsObject, options_.comment.c_str(), + reinterpret_cast(xmlNodeGetContent(curNode))); + bFlag = true; + } + } else if (curNode->type == xmlElementType::XML_CDATA_SECTION_NODE && !options_.ignoreCdata) { + if (xmlNodeGetContent(curNode) != nullptr) { + SetKeyValue(elementsObject, options_.cdata, + reinterpret_cast(xmlNodeGetContent(curNode))); + bFlag = true; + } } - } else { - SetKeyValue(elementsObject, m_Options.type, GetNodeType(curNode->type)); } - if ((curNode->type != xmlElementType::XML_COMMENT_NODE) && - (curNode->type != xmlElementType::XML_CDATA_SECTION_NODE)) { - if (!(curNode->type == xmlElementType::XML_PI_NODE && m_Options.ignoreInstruction)) { - SetKeyValue(elementsObject, m_Options.name, (char*)curNode->name); + void ConvertXml::SetNodeInfo(xmlNodePtr curNode, const napi_value &elementsObject) const + { + if (curNode->type == xmlElementType::XML_TEXT_NODE) { + return; + } else { + if (curNode->type == xmlElementType::XML_PI_NODE) { + if (!options_.ignoreInstruction) { + SetKeyValue(elementsObject, options_.type, GetNodeType(curNode->type)); + } + } else { + SetKeyValue(elementsObject, options_.type, GetNodeType(curNode->type)); + } + if ((curNode->type != xmlElementType::XML_COMMENT_NODE) && + (curNode->type != xmlElementType::XML_CDATA_SECTION_NODE)) { + if (!(curNode->type == xmlElementType::XML_PI_NODE && options_.ignoreInstruction)) { + SetKeyValue(elementsObject, options_.name, reinterpret_cast(curNode->name)); + } + } } } -} -void ConvertXml::SetEndInfo(xmlNodePtr curNode, napi_value &elementsObject, bool &bFlag, bool &bText, int32_t index) -{ - SetKeyValue(elementsObject, m_Options.type, GetNodeType(curNode->type)); - if (curNode->type == xmlElementType::XML_ELEMENT_NODE) { - SetKeyValue(elementsObject, m_Options.name.c_str(), (const char*)curNode->name); - bFlag = true; - } else if (curNode->type == xmlElementType::XML_TEXT_NODE) { - if (m_Options.trim) { - SetKeyValue(elementsObject, m_Options.text, Trim((const char*)xmlNodeGetContent(curNode))); - } else { - SetKeyValue(elementsObject, m_Options.text, (const char*)xmlNodeGetContent(curNode)); - } - if (!m_Options.ignoreText) { + void ConvertXml::SetEndInfo(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const + { + SetKeyValue(elementsObject, options_.type, GetNodeType(curNode->type)); + if (curNode->type == xmlElementType::XML_ELEMENT_NODE) { + SetKeyValue(elementsObject, options_.name.c_str(), + reinterpret_cast(curNode->name)); bFlag = true; - } - if (index != 0) { - bText = false; + } else if (curNode->type == xmlElementType::XML_TEXT_NODE) { + if (options_.trim) { + if (xmlNodeGetContent(curNode) != nullptr) { + SetKeyValue(elementsObject, options_.text, + Trim(reinterpret_cast(xmlNodeGetContent(curNode)))); + } + } else { + if (xmlNodeGetContent(curNode) != nullptr) { + SetKeyValue(elementsObject, options_.text, + reinterpret_cast(xmlNodeGetContent(curNode))); + } + } + if (!options_.ignoreText) { + bFlag = true; + } } } -} -void ConvertXml::SetPrevInfo(napi_value &recvElement, int flag, int32_t &index1) -{ - if (!m_prevObj.empty() && !flag) { - for (int i = (m_prevObj.size() - 1); i >= 0; --i) { - napi_set_element(env_, recvElement, index1++, m_prevObj[i]); + void ConvertXml::SetPrevInfo(const napi_value &recvElement, int flag, int32_t &index1) const + { + if (!prevObj_.empty() && !flag) { + for (int i = (prevObj_.size() - 1); i >= 0; --i) { + napi_set_element(env_, recvElement, index1++, prevObj_[i]); + } } } -} -void ConvertXml::GetXMLInfo(xmlNodePtr curNode, napi_value &object, int flag) -{ - napi_value elements = nullptr; - napi_create_array(env_, &elements); - napi_value recvElement; - napi_create_array(env_, &recvElement); - xmlNodePtr pNode = curNode; - int32_t index = 0; - int32_t index1 = 0; - bool bFlag = false; - bool bText = true; - while (pNode != nullptr) { - bFlag = false; - bText = true; - napi_value elementsObject = nullptr; - napi_create_object(env_, &elementsObject); - if (flag == 0 || (index % 2 != 0)) { // 2:pNode + void ConvertXml::GetXMLInfo(xmlNodePtr curNode, const napi_value &object, int flag) + { + napi_value elements = nullptr; + napi_create_array(env_, &elements); + napi_value recvElement = nullptr; + napi_create_array(env_, &recvElement); + xmlNodePtr pNode = curNode; + int32_t index = 0; + int32_t index1 = 0; + bool bFlag = false; + while (pNode != nullptr) { + bFlag = false; + napi_value elementsObject = nullptr; + napi_create_object(env_, &elementsObject); SetNodeInfo(pNode, elementsObject); - } - SetAttributes(pNode, elementsObject); - napi_value tempElement = nullptr; - napi_create_array(env_, &tempElement); - napi_value elementObj = nullptr; - napi_create_object(env_, &elementObj); - if (xmlNodeGetContent(pNode) != nullptr) { - if (pNode->children != nullptr) { - curNode = pNode->children; - GetXMLInfo(curNode, elementsObject, 1); - bFlag = true; - } else if (index % 2 != 0) { // 2:pNode - SetXmlElementType(pNode, elementsObject, bFlag); - } else if (pNode->next == nullptr) { - SetEndInfo(pNode, elementsObject, bFlag, bText, index); + SetAttributes(pNode, elementsObject); + napi_value tempElement = nullptr; + napi_create_array(env_, &tempElement); + napi_value elementObj = nullptr; + napi_create_object(env_, &elementObj); + if (xmlNodeGetContent(pNode) != nullptr) { + if (pNode->children != nullptr) { + curNode = pNode->children; + GetXMLInfo(curNode, elementsObject, 1); + bFlag = true; + } else { + SetXmlElementType(pNode, elementsObject, bFlag); + SetEndInfo(pNode, elementsObject, bFlag); + } } - } - SetPrevInfo(recvElement, flag, index1); - if (elementsObject != nullptr && bFlag && bText) { + SetPrevInfo(recvElement, flag, index1); + if (elementsObject != nullptr && bFlag) { napi_set_element(env_, recvElement, index1++, elementsObject); elementsObject = nullptr; + } + index++; + pNode = pNode->next; + } + if (bFlag) { + napi_set_named_property(env_, object, options_.elements.c_str(), recvElement); } - index++; - pNode = pNode->next; - } - if (bFlag) { - napi_set_named_property(env_, object, m_Options.elements.c_str(), recvElement); } -} -napi_value ConvertXml::convert(std::string strXml) -{ - xmlDocPtr doc = NULL; - xmlNodePtr curNode = NULL; - napi_status status = napi_ok; - size_t len = strXml.size(); - doc = xmlParseMemory(strXml.c_str(), len); - if (!doc) { - xmlFreeDoc(doc); + void ConvertXml::SetSpacesInfo(const napi_value &object) const + { + napi_value iTemp = nullptr; + switch (spaceType_) { + case (SpaceType::T_INT32): + napi_create_int32(env_, iSpace_, &iTemp); + napi_set_named_property(env_, object, "spaces", iTemp); + break; + case (SpaceType::T_STRING): + SetKeyValue(object, "spaces", strSpace_); + break; + case (SpaceType::T_INIT): + SetKeyValue(object, "spaces", strSpace_); + break; + default: + break; + } } - napi_value object = nullptr; - status = napi_create_object(env_, &object); - if (status != napi_ok) { - return NULL; + + napi_value ConvertXml::Convert(std::string strXml) + { + xmlDocPtr doc = nullptr; + xmlNodePtr curNode = nullptr; + napi_status status = napi_ok; + napi_value object = nullptr; + status = napi_create_object(env_, &object); + if (status != napi_ok) { + return nullptr; + } + Replace(strXml, "\\r", "\r"); + Replace(strXml, "\\n", "\n"); + Replace(strXml, "\\v", "\v"); + Replace(strXml, "]]> version != nullptr) { + SetKeyValue(subSubObject, "version", (const char*)doc->version); + } + if (doc != nullptr && doc->encoding != nullptr) { + SetKeyValue(subSubObject, "encoding", (const char*)doc->encoding); + } + if (!options_.ignoreDeclaration && strXml.find("xml") != std::string::npos) { + napi_set_named_property(env_, subObject, options_.attributes.c_str(), subSubObject); + napi_set_named_property(env_, object, options_.declaration.c_str(), subObject); + } + if (doc != nullptr) { + curNode = xmlDocGetRootElement(doc); + GetPrevNodeList(curNode); + GetXMLInfo(curNode, object, 0); + } + SetSpacesInfo(object); + return object; } - napi_value subObject = nullptr; - napi_value subSubObject = nullptr; - napi_value napiKey = nullptr; - napi_create_object(env_, &subSubObject); - napi_create_object(env_, &subObject); - napi_create_string_utf8(env_, (const char*)doc->version, NAPI_AUTO_LENGTH, &napiKey); - napi_set_named_property(env_, subSubObject, "version", napiKey); - napi_create_string_utf8(env_, (const char*)doc->encoding, NAPI_AUTO_LENGTH, &napiKey); - napi_set_named_property(env_, subSubObject, "encoding", napiKey); - if (!m_Options.ignoreDeclaration) { - napi_set_named_property(env_, subObject, m_Options.attributes.c_str(), subSubObject); - napi_set_named_property(env_, object, m_Options.declaration.c_str(), subObject); + + napi_status ConvertXml::DealNapiStrValue(const napi_value napi_StrValue, std::string &result) const + { + char *buffer = nullptr; + size_t bufferSize = 0; + napi_status status = napi_ok; + status = napi_get_value_string_utf8(env_, napi_StrValue, nullptr, -1, &bufferSize); + if (status != napi_ok) { + return status; + } + if (bufferSize > 0) { + buffer = new char[bufferSize + 1]; + napi_get_value_string_utf8(env_, napi_StrValue, buffer, bufferSize + 1, &bufferSize); + } + if (buffer != nullptr) { + result = buffer; + delete []buffer; + buffer = nullptr; + } + return status; } - curNode = xmlDocGetRootElement(doc); - GetPrevNodeList(curNode); - GetXMLInfo(curNode, object, 0); - napi_value iTemp = nullptr; - switch (m_SpaceType) { - case (SpaceType::T_INT32): - napi_create_int32(env_, m_iSpace, &iTemp); - napi_set_named_property(env_, object, "spaces", iTemp); - break; - case (SpaceType::T_STRING): - SetKeyValue(object, "spaces", m_strSpace); - break; - case (SpaceType::T_INIT): - SetKeyValue(object, "spaces", m_strSpace); - break; - default: - break; + + void ConvertXml::DealSpaces(const napi_value napiObj) + { + napi_value recvTemp = nullptr; + napi_get_named_property(env_, napiObj, "spaces", &recvTemp); + napi_valuetype valuetype = napi_undefined; + napi_typeof(env_, recvTemp, &valuetype); + if (valuetype == napi_string) { + DealNapiStrValue(recvTemp, strSpace_); + spaceType_ = SpaceType::T_STRING; + } else if (valuetype == napi_number) { + int32_t iTemp; + if (napi_get_value_int32(env_, recvTemp, &iTemp) == napi_ok) { + iSpace_ = iTemp; + spaceType_ = SpaceType::T_INT32; + } + } } - return object; -} -napi_status ConvertXml::DealNapiStrValue(napi_value napi_StrValue, std::string &result) -{ - char *buffer = nullptr; - size_t bufferSize = 0; - napi_status status = napi_ok; - status = napi_get_value_string_utf8(env_, napi_StrValue, nullptr, -1, &bufferSize); - if (status != napi_ok) { - return status; + void ConvertXml::DealIgnore(const napi_value napiObj) + { + std::vector vctIgnore = {"compact", "trim", "ignoreDeclaration", "ignoreInstruction", + "ignoreAttributes", "ignoreComment", "ignoreCdata", + "ignoreDoctype", "ignoreText"}; + size_t vctLength = vctIgnore.size(); + for (size_t i = 0; i < vctLength; ++i) { + napi_value recvTemp = nullptr; + bool bRecv = false; + napi_get_named_property(env_, napiObj, vctIgnore[i].c_str(), &recvTemp); + if ((napi_get_value_bool(env_, recvTemp, &bRecv)) == napi_ok) { + switch (i) { + case 0: + options_.compact = bRecv; + break; + case 1: // 1:trim + options_.trim = bRecv; + break; + case 2: // 2:ignoreDeclaration + options_.ignoreDeclaration = bRecv; + break; + case 3: // 3:ignoreInstruction + options_.ignoreInstruction = bRecv; + break; + case 4: // 4:ignoreAttributes + options_.ignoreAttributes = bRecv; + break; + case 5: // 5:ignoreComment + options_.ignoreComment = bRecv; + break; + case 6: // 6:ignoreCdata + options_.ignoreCdata = bRecv; + break; + case 7: // 7:ignoreDoctype + options_.ignoreDoctype = bRecv; + break; + case 8: // 8:ignoreText + options_.ignoreText = bRecv; + break; + default: + break; + } + } + } } - buffer = new char[bufferSize + 1]; - napi_get_value_string_utf8(env_, napi_StrValue, buffer, bufferSize + 1, &bufferSize); - if (buffer != nullptr) { - result = buffer; - delete []buffer; - buffer = nullptr; + void ConvertXml::SetDefaultKey(size_t i, const std::string strRecv) + { + switch (i) { + case 0: + options_.declaration = strRecv; + break; + case 1: + options_.instruction = strRecv; + break; + case 2: // 2:attributes + options_.attributes = strRecv; + break; + case 3: // 3:text + options_.text = strRecv; + break; + case 4: // 4:cdata + options_.cdata = strRecv; + break; + case 5: // 5:doctype + options_.doctype = strRecv; + break; + case 6: // 6:comment + options_.comment = strRecv; + break; + case 7: // 7:parent + options_.parent = strRecv; + break; + case 8: // 8:type + options_.type = strRecv; + break; + case 9: // 9:name + options_.name = strRecv; + break; + case 10: // 10:elements + options_.elements = strRecv; + break; + default: + break; + } } - return status; -} -void ConvertXml::DealSpaces(napi_value napi_obj) -{ - napi_value recvTemp = nullptr; - napi_get_named_property(env_, napi_obj, "spaces", &recvTemp); - napi_valuetype valuetype = napi_undefined; - napi_typeof(env_, recvTemp, &valuetype); - if (valuetype == napi_string) { - DealNapiStrValue(recvTemp, m_strSpace); - m_SpaceType = SpaceType::T_STRING; - } else if (valuetype == napi_number) { - int32_t iTemp; - if (napi_get_value_int32(env_, recvTemp, &iTemp) == napi_ok) { - m_iSpace = iTemp; - m_SpaceType = SpaceType::T_INT32; + void ConvertXml::DealOptions(const napi_value napiObj) + { + std::vector vctOptions = {"declarationKey", "instructionKey", "attributesKey", "textKey", + "cdataKey", "doctypeKey", "commentKey", "parentKey", "typeKey", + "nameKey", "elementsKey"}; + size_t vctLength = vctOptions.size(); + for (size_t i = 0; i < vctLength; ++i) { + napi_value recvTemp = nullptr; + std::string strRecv = ""; + napi_get_named_property(env_, napiObj, vctOptions[i].c_str(), &recvTemp); + if ((DealNapiStrValue(recvTemp, strRecv)) == napi_ok) { + SetDefaultKey(i, strRecv); + } } + DealIgnore(napiObj); + DealSpaces(napiObj); } -} -void ConvertXml::DealIgnore(napi_value napi_obj) -{ - std::vectorvctIgnore = { "compact", "trim", "ignoreDeclaration", "ignoreInstruction", - "ignoreAttributes", "ignoreComment", "ignoreCdata", "ignoreDoctype", "ignoreText" }; - for (size_t i = 0; i < vctIgnore.size(); ++i) { - napi_value recvTemp = nullptr; - bool bRecv = false; - napi_get_named_property(env_, napi_obj, vctIgnore[i].c_str(), &recvTemp); - if ((napi_get_value_bool(env_, recvTemp, &bRecv)) == napi_ok) { - switch (i) { - case 0: - m_Options.compact = bRecv; - break; - case 1: // 1:trim - m_Options.trim = bRecv; - break; - case 2: // 2:ignoreDeclaration - m_Options.ignoreDeclaration = bRecv; - break; - case 3: // 3:ignoreInstruction - m_Options.ignoreInstruction = bRecv; - break; - case 4: // 4:ignoreAttributes - m_Options.ignoreAttributes = bRecv; - break; - case 5: // 5:ignoreComment - m_Options.ignoreComment = bRecv; - break; - case 6: // 6:ignoreCdata - m_Options.ignoreCdata = bRecv; - break; - case 7: // 7:ignoreDoctype - m_Options.ignoreDoctype = bRecv; - break; - case 8: // 8:ignoreText - m_Options.ignoreText = bRecv; - break; - default: - break; + void ConvertXml::DealSingleLine(std::string &strXml, const napi_value &object) + { + size_t iXml = 0; + if ((iXml = strXml.find("xml")) != std::string::npos) { + xmlInfo_.bXml = true; + napi_value declObj = nullptr; + napi_create_object(env_, &declObj); + napi_value attrObj = nullptr; + bool bFlag = false; + napi_create_object(env_, &attrObj); + if (strXml.find("version=") != std::string::npos) { + xmlInfo_.bVersion = true; + SetKeyValue(attrObj, "version", "1.0"); + bFlag = true; + } + if (strXml.find("encoding=") != std::string::npos) { + xmlInfo_.bEncoding = false; + SetKeyValue(attrObj, "encoding", "utf-8"); + bFlag = true; + } + if (bFlag) { + napi_set_named_property(env_, declObj, options_.attributes.c_str(), attrObj); + napi_set_named_property(env_, object, options_.declaration.c_str(), declObj); + } else { + napi_set_named_property(env_, object, options_.declaration.c_str(), declObj); + } + if (strXml.find(">", iXml) == strXml.size() - 1) { + strXml = ""; + } else { + strXml = strXml.substr(0, strXml.rfind("<", iXml)) + strXml.substr(strXml.find(">", iXml) + 1); + } + } + size_t iCount = 0; + size_t iLen = strXml.size(); + for (; iCount < iLen; ++iCount) { + if (strXml[iCount] != ' ' && strXml[iCount] != '\v' && + strXml[iCount] != '\t' && strXml[iCount] != '\n') { + break; } } + if (iCount < iLen) { + DealComplex(strXml, object); + } } -} -void ConvertXml::SetDefaultKey(size_t i, std::string strRecv) -{ - switch (i) { - case 0: - m_Options.declaration = strRecv; - break; - case 1: - m_Options.instruction = strRecv; - break; - case 2: // 2:attributes - m_Options.attributes = strRecv; - break; - case 3: // 3:text - m_Options.text = strRecv; - break; - case 4: // 4:cdata - m_Options.cdata = strRecv; - break; - case 5: // 5:doctype - m_Options.doctype = strRecv; - break; - case 6: // 6:comment - m_Options.comment = strRecv; - break; - case 7: // 7:parent - m_Options.parent = strRecv; - break; - case 8: // 8:type - m_Options.type = strRecv; - break; - case 9: // 9:name - m_Options.name = strRecv; - break; - case 10: // 10:elements - m_Options.elements = strRecv; - break; - default: - break; + void ConvertXml::DealComplex(std::string &strXml, const napi_value &object) const + { + if (strXml.find(""; + } else { + strXml = "" + strXml + ""; + } + xmlDocPtr doc = nullptr; + xmlNodePtr curNode = nullptr; + size_t len = strXml.size(); + doc = xmlParseMemory(strXml.c_str(), len); + if (!doc) { + xmlFreeDoc(doc); + } + if (doc) { + curNode = xmlDocGetRootElement(doc); + curNode = curNode->children; + napi_value elements = nullptr; + napi_create_array(env_, &elements); + bool bHasEle = false; + int index = 0; + bool bCData = false; + if (strXml.find("vctOptions = { "declarationKey", "instructionKey", "attributesKey", "textKey", - "cdataKey", "doctypeKey", "commentKey", "parentKey", "typeKey", "nameKey", "elementsKey" }; - for (size_t i = 0; i < vctOptions.size(); ++i) { - napi_value recvTemp = nullptr; - std::string strRecv = ""; - napi_get_named_property(env_, napi_obj, vctOptions[i].c_str(), &recvTemp); - if ((DealNapiStrValue(recvTemp, strRecv)) == napi_ok) { - SetDefaultKey(i, strRecv); + void ConvertXml::Replace(std::string &str, const std::string src, const std::string dst) const + { + size_t index = 0; + while ((index = str.find(src)) != std::string::npos) { + str.replace(index, src.size(), dst); } } - DealIgnore(napi_obj); - DealSpaces(napi_obj); -} + + void ConvertXml::DealCDataInfo(bool bCData, xmlNodePtr &curNode) const + { + if (bCData && curNode->type == xmlElementType::XML_CDATA_SECTION_NODE && + curNode->next && curNode->next->type == xmlElementType::XML_TEXT_NODE && + curNode->next->next && curNode->next->next->type == xmlElementType::XML_CDATA_SECTION_NODE) { + if (xmlNodeGetContent(curNode->next) != nullptr) { + std::string strTemp = reinterpret_cast(xmlNodeGetContent(curNode->next)); + Replace(strTemp, " ", ""); + Replace(strTemp, "\v", ""); + Replace(strTemp, "\t", ""); + Replace(strTemp, "\n", ""); + if (strTemp == "") { + curNode = curNode->next->next; + } + } + } else { + curNode = curNode->next; + } + } +} // namespace \ No newline at end of file diff --git a/convertxml/js_convertxml.h b/convertxml/js_convertxml.h index bbe2381f45ee7f6bed5299e47fec8a62e98ed162..2fb1a68491feb4487a7b4d2c5bbbe48743b3dc35 100755 --- a/convertxml/js_convertxml.h +++ b/convertxml/js_convertxml.h @@ -17,74 +17,89 @@ #include #include -#include -#include "napi/native_api.h" -#include "napi/native_node_api.h" #include "libxml/parser.h" #include "libxml/tree.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" -enum class SpaceType { - T_INT32, - T_STRING, - T_INIT = -1 -}; +namespace OHOS::Xml { + enum class SpaceType { + T_INT32, + T_STRING, + T_INIT = -1 + }; struct Options { - std::string declaration = "_declaration"; - std::string instruction = "_instruction"; - std::string attributes = "_attributes"; - std::string text = "_text"; - std::string cdata = "_cdata"; - std::string doctype = "_doctype"; - std::string comment = "_comment"; - std::string parent = "_parent"; - std::string type = "_type"; - std::string name = "_name"; - std::string elements = "_elements"; - bool compact = false; - bool trim = false; - bool nativetype = false; - bool nativetypeattributes = false; - bool addparent = false; - bool alwaysArray = false; - bool alwaysChildren = false; - bool instructionHasAttributes = false; - bool ignoreDeclaration = false; - bool ignoreInstruction = false; - bool ignoreAttributes = false; - bool ignoreComment = false; - bool ignoreCdata = false; - bool ignoreDoctype = false; - bool ignoreText = false; - bool spaces = false; + std::string declaration = "_declaration"; + std::string instruction = "_instruction"; + std::string attributes = "_attributes"; + std::string text = "_text"; + std::string cdata = "_cdata"; + std::string doctype = "_doctype"; + std::string comment = "_comment"; + std::string parent = "_parent"; + std::string type = "_type"; + std::string name = "_name"; + std::string elements = "_elements"; + bool compact = false; + bool trim = false; + bool nativetype = false; + bool nativetypeattributes = false; + bool addparent = false; + bool alwaysArray = false; + bool alwaysChildren = false; + bool instructionHasAttributes = false; + bool ignoreDeclaration = false; + bool ignoreInstruction = false; + bool ignoreAttributes = false; + bool ignoreComment = false; + bool ignoreCdata = false; + bool ignoreDoctype = false; + bool ignoreText = false; + bool spaces = false; }; -class ConvertXml { -public: - explicit ConvertXml(napi_env env); - virtual ~ConvertXml() {} - void SetAttributes(xmlNodePtr curNode, napi_value &elementsObject); - void SetXmlElementType(xmlNodePtr curNode, napi_value &elementsObject, bool &bFlag); - void SetNodeInfo(xmlNodePtr curNode, napi_value &elementsObject); - void SetEndInfo(xmlNodePtr curNode, napi_value &elementsObject, bool &bFlag, bool &bText, int32_t index); - void GetXMLInfo(xmlNodePtr curNode, napi_value &object, int flag = 0); - napi_value convert(std::string strXml); - std::string GetNodeType(xmlElementType enumType); - napi_status DealNapiStrValue(napi_value napi_StrValue, std::string &result); - void SetKeyValue(napi_value &object, std::string strKey, std::string strValue); - void DealOptions(napi_value napi_obj); - std::string Trim(std::string strXmltrim); - void GetPrevNodeList(xmlNodePtr curNode); - void DealSpaces(napi_value napi_obj); - void DealIgnore(napi_value napi_obj); - void SetPrevInfo(napi_value &recvElement, int flag, int32_t &index1); - void SetDefaultKey(size_t i, std::string strRecv); -private: - napi_env env_; - SpaceType m_SpaceType; - int32_t m_iSpace; - std::string m_strSpace; - Options m_Options; - std::vector m_prevObj; +struct XmlInfo { + bool bXml = false; + bool bVersion = false; + std::string strVersion = ""; + bool bEncoding = false; + std::string strEncoding = ""; }; + + class ConvertXml { + public: + explicit ConvertXml(napi_env env); + virtual ~ConvertXml() {} + void SetAttributes(xmlNodePtr curNode, const napi_value &elementsObject) const; + void SetXmlElementType(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const; + void SetNodeInfo(xmlNodePtr curNode, const napi_value &elementsObject) const; + void SetEndInfo(xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const; + void GetXMLInfo(xmlNodePtr curNode, const napi_value &object, int flag = 0); + napi_value Convert(std::string strXml); + std::string GetNodeType(const xmlElementType enumType) const; + napi_status DealNapiStrValue(const napi_value napi_StrValue, std::string &result) const; + void SetKeyValue(const napi_value &object, const std::string strKey, const std::string strValue) const; + void DealOptions(const napi_value napiObj); + std::string Trim(std::string strXmltrim) const; + void GetPrevNodeList(xmlNodePtr curNode); + void DealSpaces(const napi_value napiObj); + void DealIgnore(const napi_value napiObj); + void SetPrevInfo(const napi_value &recvElement, int flag, int32_t &index1) const; + void SetDefaultKey(size_t i, const std::string strRecv); + void SetSpacesInfo(const napi_value &object) const; + void DealSingleLine(std::string &strXml, const napi_value &object); + void DealComplex(std::string &strXml, const napi_value &object) const; + void Replace(std::string &str, const std::string src, const std::string dst) const; + void DealCDataInfo(bool bCData, xmlNodePtr &curNode) const; + private: + napi_env env_; + SpaceType spaceType_; + int32_t iSpace_; + std::string strSpace_; + Options options_; + std::vector prevObj_; + XmlInfo xmlInfo_; + }; +} // namespace #endif \ No newline at end of file diff --git a/convertxml/js_convertxml.js b/convertxml/js_convertxml.js deleted file mode 100755 index a0305b036471c70e26b7e2e989878f63a6464e36..0000000000000000000000000000000000000000 --- a/convertxml/js_convertxml.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; -const convertXml = requireInternal("ConvertXML"); -class ConvertXml { - convertxmlclass; - constructor() { - this.convertxmlclass = new convertXml.ConvertXml(); - } - convert(strXml, options) { - let converted = this.convertxmlclass.convert(strXml, options); - let space = 0; - if (converted.hasOwnProperty("spaces")) { - space = converted.spaces; - delete converted.spaces; - } - return JSON.stringify(converted, null, space); - } -} - -export default { - ConvertXml : ConvertXml -} - - diff --git a/convertxml/native_module_convertxml.cpp b/convertxml/native_module_convertxml.cpp index 25223d8adad4cf2b0b437238bfab6b4d63aaa71f..4568b8382c54da544c4c3ba3095eb7ec6c41ecac 100755 --- a/convertxml/native_module_convertxml.cpp +++ b/convertxml/native_module_convertxml.cpp @@ -12,101 +12,116 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "js_convertxml.h" + #include "utils/log.h" +#include "js_convertxml.h" #include "napi/native_api.h" #include "napi/native_node_api.h" extern const char _binary_js_convertxml_js_start[]; extern const char _binary_js_convertxml_js_end[]; +extern const char _binary_convertxml_abc_start[]; +extern const char _binary_convertxml_abc_end[]; -static napi_value ConvertXmlConstructor(napi_env env, napi_callback_info info) -{ - napi_value thisVar = nullptr; - void *data = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, &data); - auto objectInfo = new ConvertXml(env); - napi_wrap( - env, thisVar, objectInfo, - [](napi_env env, void *data, void *hint) { - auto obj = (ConvertXml*)data; - if (obj != nullptr) { - delete obj; - } - }, - nullptr, nullptr); - return thisVar; -} - -static napi_value Convert(napi_env env, napi_callback_info info) -{ - napi_value thisVar = nullptr; - size_t requireMaxArgc = 2; - size_t requireMinArgc = 1; - size_t argc = 2; - napi_value args[2] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - NAPI_ASSERT(env, argc <= requireMaxArgc, "Wrong number of arguments(Over)"); - NAPI_ASSERT(env, argc >= requireMinArgc, "Wrong number of arguments(Less)"); - std::string strXml; - napi_valuetype valuetype; - ConvertXml *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); - if (args[0] == nullptr) { - NAPI_CALL(env, napi_throw_error(env, "", "parameter is empty")); - } else { - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument typr. String expected."); - object->DealNapiStrValue(args[0], strXml); +namespace OHOS::Xml { + static napi_value ConvertXmlConstructor(napi_env env, napi_callback_info info) + { + napi_value thisVar = nullptr; + void *data = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, &data); + auto objectInfo = new ConvertXml(env); + napi_wrap( + env, thisVar, objectInfo, + [](napi_env env, void *data, void *hint) { + auto obj = (ConvertXml*)data; + if (obj != nullptr) { + delete obj; + } + }, + nullptr, nullptr); + return thisVar; } - if (args[1] != nullptr) { - object->DealOptions(args[1]); + + static napi_value Convert(napi_env env, napi_callback_info info) + { + napi_value thisVar = nullptr; + size_t requireMaxArgc = 2; // 2:MaxArgc + size_t requireMinArgc = 1; + size_t argc = 2; + napi_value args[2] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); + NAPI_ASSERT(env, argc <= requireMaxArgc, "Wrong number of arguments(Over)"); + NAPI_ASSERT(env, argc >= requireMinArgc, "Wrong number of arguments(Less)"); + std::string strXml; + napi_valuetype valuetype; + ConvertXml *object = nullptr; + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&object))); + if (args[0] == nullptr) { + NAPI_CALL(env, napi_throw_error(env, "", "parameter is empty")); + } else { + NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument typr. String expected."); + object->DealNapiStrValue(args[0], strXml); + } + if (args[1] != nullptr) { + object->DealOptions(args[1]); + } + napi_value result = object->Convert(strXml); + return result; } - napi_value result = object->convert(strXml); - return result; -} -static napi_value ConvertXmlInit(napi_env env, napi_value exports) -{ - const char *ConvertXmlClassName = "ConvertXml"; - napi_value ConvertXmlClass = nullptr; - static napi_property_descriptor ConvertXmlDesc[] = { - DECLARE_NAPI_FUNCTION("convert", Convert) - }; - NAPI_CALL(env, napi_define_class(env, ConvertXmlClassName, strlen(ConvertXmlClassName), ConvertXmlConstructor, - nullptr, sizeof(ConvertXmlDesc) / sizeof(ConvertXmlDesc[0]), ConvertXmlDesc, - &ConvertXmlClass)); - static napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("ConvertXml", ConvertXmlClass) - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - return exports; -} - -extern "C" -__attribute__((visibility("default"))) void NAPI_convertxml_GetJSCode(const char **buf, int *bufLen) -{ - if (buf != nullptr) { - *buf = _binary_js_convertxml_js_start; + static napi_value ConvertXmlInit(napi_env env, napi_value exports) + { + const char *convertXmlClassName = "ConvertXml"; + napi_value convertXmlClass = nullptr; + static napi_property_descriptor convertXmlDesc[] = { + DECLARE_NAPI_FUNCTION("convert", Convert) + }; + NAPI_CALL(env, napi_define_class(env, convertXmlClassName, strlen(convertXmlClassName), ConvertXmlConstructor, + nullptr, sizeof(convertXmlDesc) / sizeof(convertXmlDesc[0]), convertXmlDesc, + &convertXmlClass)); + static napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("ConvertXml", convertXmlClass) + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; } - if (bufLen != nullptr) { - *bufLen = _binary_js_convertxml_js_end - _binary_js_convertxml_js_start; - } -} + extern "C" + __attribute__((visibility("default"))) void NAPI_convertxml_GetJSCode(const char **buf, int *bufLen) + { + if (buf != nullptr) { + *buf = _binary_js_convertxml_js_start; + } -static napi_module ConvertXmlModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = ConvertXmlInit, - .nm_modname = "ConvertXML", - .nm_priv = ((void*)0), - .reserved = { 0 }, -}; + if (bufLen != nullptr) { + *bufLen = _binary_js_convertxml_js_end - _binary_js_convertxml_js_start; + } + } + extern "C" + __attribute__((visibility("default"))) void NAPI_convertxml_GetABCCode(const char** buf, int* buflen) + { + if (buf != nullptr) { + *buf = _binary_convertxml_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_convertxml_abc_end - _binary_convertxml_abc_start; + } + } -extern "C" __attribute__ ((constructor)) void RegisterModule() { - napi_module_register(&ConvertXmlModule); -} + static napi_module convertXmlModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = ConvertXmlInit, + .nm_modname = "ConvertXML", + .nm_priv = ((void*)0), + .reserved = { 0 }, + }; + extern "C" __attribute__ ((constructor)) void RegisterModule() + { + napi_module_register(&convertXmlModule); + } +} // namespace \ No newline at end of file diff --git a/convertxml/src/js_convertxml.ts b/convertxml/src/js_convertxml.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e9b4c0376e978a9899257ada7fd30aa5d55205e --- /dev/null +++ b/convertxml/src/js_convertxml.ts @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare function requireInternal(s : string) : any; +const convertXml = requireInternal("ConvertXML"); +class ConvertXml { + convertxmlclass; + constructor() { + this.convertxmlclass = new convertXml.ConvertXml(); + } + convert(strXml : string, options : any) { + strXml = DealXml(strXml); + let converted = this.convertxmlclass.convert(strXml, options); + let space = 0; + if (converted.hasOwnProperty("spaces")) { + space = converted.spaces; + delete converted.spaces; + } + var strEnd = JSON.stringify(converted, null, space); + var idx = 0; + while ((idx = strEnd.indexOf('\\t')) != -1) { + strEnd = strEnd.substring(0, idx) + '\t' + strEnd.substring(idx + 2); + } + while ((idx = strEnd.indexOf('\\n')) != -1) { + strEnd = strEnd.substring(0, idx) + '\n' + strEnd.substring(idx + 2); + } + while ((idx = strEnd.indexOf('\\')) != -1) { + strEnd = strEnd.substring(0, idx) + '' + strEnd.substring(idx + 1); + } + return strEnd; + } +} + +function DealXml(strXml : string) +{ + var idx = 0; + var idxSec = 0; + var idxThir = 0; + var idxCData = 0; + var idxCDataSec = 0; + while ((idx = strXml.indexOf(']]>', idxSec)) != -1) { + idxThir = strXml.indexOf('<', idx); + strXml = DealPriorReplace(strXml, idx, idxThir); + if (strXml.indexOf('<', idx) != -1) { + idxCData = strXml.indexOf('', idxCData); + strXml = DealLaterReplace(strXml, idx, idxThir); + idxCDataSec = idxSec; + } + } + else { + break; + } + } + return strXml; +} + +function DealPriorReplace(strXml : string, idx : any, idxThir : any) +{ + var i = idx + 1; + for (; i < idxThir ; i++) { + var cXml = strXml.charAt(i); + if (cXml != '\n' && cXml != '\v' && cXml != '\t' && cXml != ' ') + { + break; + } + } + var j = idx + 1; + for (; j < strXml.indexOf('<', idx) ; j++) { + var cXml = strXml.charAt(j); + if (i != idxThir) { + switch (cXml) { + case '\n': + strXml = strXml.substring(0, j) + '\\n' + strXml.substring(j + 1); + break; + case '\v': + strXml = strXml.substring(0, j) + '\\v' + strXml.substring(j + 1); + break; + case '\t': + strXml = strXml.substring(0, j) + '\\t' + strXml.substring(j + 1); + break; + default: + break; + } + } else { + strXml = strXml.substring(0, j) + strXml.substring(j + 1); + --j; + } + } + return strXml; +} + +function DealLaterReplace(strXml, idx, idxThir) +{ + var i = idx + 1; + for (; i < idxThir ; i++) { + var cXml = strXml.charAt(i) + switch (cXml) { + case '\n': + strXml = strXml.substring(0, i) + '\\n' + strXml.substring(i + 1); + break; + case '\v': + strXml = strXml.substring(0, i) + '\\v' + strXml.substring(i + 1); + break; + case '\t': + strXml = strXml.substring(0, i) + '\\t' + strXml.substring(i + 1); + break; + default: + break; + } + } + return strXml; +} + +export default { + ConvertXml : ConvertXml +} + + diff --git a/convertxml/tsconfig.json b/convertxml/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..c86e350c8cabc34f78dcfe27b31f16b871fd28c1 --- /dev/null +++ b/convertxml/tsconfig.json @@ -0,0 +1,15 @@ +{ +"compilerOptions": { + "target": "es6", + "module": "es6", + "rootDir": "./src", + //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./out", /* Specify an output folder for all emitted files. */ + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "noImplicitThis": false, + } +} + diff --git a/uri/BUILD.gn b/uri/BUILD.gn index 0249e7a398c05f7ad3fabe6685670b171ce9837a..a136c4bf7453f1930f5dd23b3380b1281f4827ac 100755 --- a/uri/BUILD.gn +++ b/uri/BUILD.gn @@ -10,15 +10,58 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") +import("//foundation/ace/ace_engine/ace_config.gni") + +# compile .ts to .js. +action("build_ts_js") { + script = "//base/compileruntime/js_api_module/uri/build_ts_js.py" + depfile = "$target_gen_dir/$target_name.d" + outputs = [ target_out_dir + "/js_uri.js" ] +} base_output_path = get_label_info(":js_uri", "target_out_dir") js_uri_obj_path = base_output_path + "/uri.o" gen_js_obj("js_uri") { - input = "//base/compileruntime/js_api_module/uri/js_uri.js" + input = "$target_out_dir/js_uri.js" output = js_uri_obj_path + dep = ":build_ts_js" +} + +# compile .js to .abc. +action("gen_uri_abc") { + visibility = [ ":*" ] + script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" + + args = [ + "--src-js", + rebase_path(target_out_dir + "/js_uri.js"), + "--dst-file", + rebase_path(target_out_dir + "/uri.abc"), + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + deps = [ + ":build_ts_js", + "//ark/ts2abc/ts2panda:ark_ts2abc_build", + ] + + inputs = [ target_out_dir + "/js_uri.js" ] + outputs = [ target_out_dir + "/uri.abc" ] +} + +abc_output_path = get_label_info(":uri_abc", "target_out_dir") +uri_abc_obj_path = abc_output_path + "/uri_abc.o" +gen_js_obj("uri_abc") { + input = "$target_out_dir/uri.abc" + output = uri_abc_obj_path + dep = ":gen_uri_abc" } ohos_shared_library("uri") { @@ -36,6 +79,7 @@ ohos_shared_library("uri") { deps = [ ":js_uri", + ":uri_abc", "//base/compileruntime/js_api_module/uri/:js_uri", "//foundation/ace/napi/:ace_napi", "//foundation/ace/napi/:ace_napi_quickjs", @@ -57,4 +101,3 @@ ohos_shared_library("uri") { group("uri_packages") { deps = [ ":uri" ] } - diff --git a/uri/build_ts_js.py b/uri/build_ts_js.py new file mode 100755 index 0000000000000000000000000000000000000000..4461b2bb9c06e96d3ca0342b084647a40377f5e1 --- /dev/null +++ b/uri/build_ts_js.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os + +if __name__ == '__main__': + + build_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir("%s/base/compileruntime/js_api_module/uri" % build_path) + os.system('../../../../developtools/ace-ets2bundle/compiler/node_modules/typescript/bin/tsc') + + if os.access("../../../../out/ohos-arm64-release", os.F_OK): + os.system('cp -r ./out/js_uri.js ../../../../out/ohos-arm64-release/obj/base/compileruntime/js_api_module/uri/js_uri.js') + + if os.access("../../../../out/ohos-arm-release", os.F_OK): + os.system('cp -r ./out/js_uri.js ../../../../out/ohos-arm-release/obj/base/compileruntime/js_api_module/uri/js_uri.js') + + os.system('rm -rf ./out') \ No newline at end of file diff --git a/uri/js_uri.cpp b/uri/js_uri.cpp index 3af8ab0c9e651343528f5e1b2bca77c21d5525ec..34452121891811f25686dfb49a533cf1a2d2b1fe 100755 --- a/uri/js_uri.cpp +++ b/uri/js_uri.cpp @@ -15,14 +15,14 @@ #include "js_uri.h" #include "utils/log.h" namespace OHOS::Uri { - std::bitset g_ruleAlpha; - std::bitset g_ruleScheme; - std::bitset g_ruleUrlc; - std::bitset g_rulePath; - std::bitset g_ruleUserInfo; - std::bitset g_ruleScope; - std::bitset g_ruleDigit; - std::bitset g_rulePort; + std::bitset g_ruleAlpha; + std::bitset g_ruleScheme; + std::bitset g_ruleUrlc; + std::bitset g_rulePath; + std::bitset g_ruleUserInfo; + std::bitset g_ruleScope; + std::bitset g_ruleDigit; + std::bitset g_rulePort; void Uri::PreliminaryWork() const { std::string digitAggregate = "0123456789"; diff --git a/uri/native_module_uri.cpp b/uri/native_module_uri.cpp index cb013be86fad1ddea9a9f16941cf4596062376e5..23eb1c6f21434628546362cc073fa77e4b5efb75 100755 --- a/uri/native_module_uri.cpp +++ b/uri/native_module_uri.cpp @@ -21,6 +21,9 @@ extern const char _binary_js_uri_js_start[]; extern const char _binary_js_uri_js_end[]; +extern const char _binary_uri_abc_start[]; +extern const char _binary_uri_abc_end[]; + namespace OHOS::Uri { static napi_value UriConstructor(napi_env env, napi_callback_info info) { @@ -49,7 +52,7 @@ namespace OHOS::Uri { } NAPI_CALL(env, napi_wrap(env, thisVar, object, [](napi_env env, void *data, void *hint) { - auto obj = (Uri*)data; + auto obj = reinterpret_cast(data); if (obj != nullptr) { delete obj; } @@ -62,7 +65,7 @@ namespace OHOS::Uri { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string normalizeUri = muri->Normalize(); napi_value result = nullptr; size_t tempLen = normalizeUri.size(); @@ -79,9 +82,9 @@ namespace OHOS::Uri { NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); Uri *other = nullptr; - NAPI_CALL(env, napi_unwrap(env, argv[0], (void**)&other)); + NAPI_CALL(env, napi_unwrap(env, argv[0], reinterpret_cast(&other))); bool flag = muri->Equals(*other); NAPI_CALL(env, napi_get_boolean(env, flag, &result)); @@ -94,7 +97,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); bool flag = muri->IsAbsolute(); NAPI_CALL(env, napi_get_boolean(env, flag, &result)); return result; @@ -106,7 +109,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->IsFailed(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -119,7 +122,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->ToString(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -132,7 +135,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetScheme(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -145,7 +148,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetAuthority(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -158,7 +161,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetSsp(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -171,7 +174,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetUserinfo(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -184,7 +187,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetHost(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -197,7 +200,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetPort(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -210,7 +213,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetPath(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -223,7 +226,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetQuery(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -236,7 +239,7 @@ namespace OHOS::Uri { napi_value result = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); Uri *muri = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&muri)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&muri))); std::string temp = muri->GetFragment(); size_t templen = temp.size(); NAPI_CALL(env, napi_create_string_utf8(env, temp.c_str(), templen, &result)); @@ -264,7 +267,7 @@ namespace OHOS::Uri { DECLARE_NAPI_GETTER("isFailed", IsFailed), }; NAPI_CALL(env, napi_define_class(env, uriClassName, strlen(uriClassName), UriConstructor, - nullptr, sizeof(uriDesc) / sizeof(uriDesc[0]), uriDesc, &uriClass)); + nullptr, sizeof(uriDesc) / sizeof(uriDesc[0]), uriDesc, &uriClass)); static napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("Uri", uriClass) }; @@ -283,7 +286,16 @@ namespace OHOS::Uri { *bufLen = _binary_js_uri_js_end - _binary_js_uri_js_start; } } - + extern "C" + __attribute__((visibility("default"))) void NAPI_uri_GetABCCode(const char** buf, int* buflen) + { + if (buf != nullptr) { + *buf = _binary_uri_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_uri_abc_end - _binary_uri_abc_start; + } + } static napi_module UriModule = { .nm_version = 1, .nm_flags = 0, diff --git a/uri/js_uri.js b/uri/src/js_uri.ts old mode 100755 new mode 100644 similarity index 91% rename from uri/js_uri.js rename to uri/src/js_uri.ts index d2603eef19d2f5384fd397d9578af7acb5d2a25c..a8ce10e82778159c9b0769bbc31c41f8e3b5d0cf --- a/uri/js_uri.js +++ b/uri/src/js_uri.ts @@ -1,105 +1,105 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; -const uri = requireInternal("uri"); - -class URI { - constructor(input) { - if (typeof input !== 'string' || input.length === 0) { - throw new Error("input type err"); - } - this.uricalss = new uri.Uri(input); - let errStr = this.uricalss.isFailed; - if (errStr.length !== 0) { - throw new Error(errStr); - } - } - toString() { - return toAscllString(this.uricalss.toString()); - } - - equals(other) { - return this.uricalss.equals(other.uricalss); - } - - isAbsolute() { - return this.uricalss.isAbsolute(); - } - - normalize() { - let uriStr = this.uricalss.normalize(); - return createNewUri(uriStr); - } - - get scheme() { - return this.uricalss.scheme; - } - - get authority() { - return this.uricalss.authority; - } - - get ssp() { - return this.uricalss.ssp; - } - - get userinfo() { - return this.uricalss.userinfo; - } - - get host() { - return this.uricalss.host; - } - - get port() { - return this.uricalss.port; - } - - get path() { - return this.uricalss.path; - } - - get query() { - return this.uricalss.query; - } - - get fragment() { - return this.uricalss.fragment; - } - -} - -function toAscllString(uriStr) { - if (uriStr.indexOf('[') !== -1) { - let arr = uriStr.split("["); - let brr = arr[1].split("]"); - arr[1] = '[' + brr[0] + ']'; - arr[2] = brr[1]; - arr[0] = encodeURI(arr[0]); - arr[2] = encodeURI(arr[2]); - return arr.join(''); - } else { - return encodeURI(uriStr); - } -} - -function createNewUri(uriStr) { - return new URI(uriStr); -} - -export default { - URI: URI, -} +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare function requireInternal(s : string) : any; +const uri = requireInternal("uri"); + +class URI { + uricalss : any + constructor(input:any) { + if (typeof input !== 'string' || input.length === 0) { + throw new Error("input type err"); + } + this.uricalss = new uri.Uri(input); + let errStr = this.uricalss.isFailed; + if (errStr.length !== 0) { + throw new Error(errStr); + } + } + toString() { + return toAscllString(this.uricalss.toString()); + } + + equals(other:any) { + return this.uricalss.equals(other.uricalss); + } + + isAbsolute() { + return this.uricalss.isAbsolute(); + } + + normalize() { + let uriStr = this.uricalss.normalize(); + return createNewUri(uriStr); + } + + get scheme() { + return this.uricalss.scheme; + } + + get authority() { + return this.uricalss.authority; + } + + get ssp() { + return this.uricalss.ssp; + } + + get userinfo() { + return this.uricalss.userinfo; + } + + get host() { + return this.uricalss.host; + } + + get port() { + return this.uricalss.port; + } + + get path() { + return this.uricalss.path; + } + + get query() { + return this.uricalss.query; + } + + get fragment() { + return this.uricalss.fragment; + } + +} + +function toAscllString(uriStr:any) { + if (uriStr.indexOf('[') !== -1) { + let arr = uriStr.split("["); + let brr = arr[1].split("]"); + arr[1] = '[' + brr[0] + ']'; + arr[2] = brr[1]; + arr[0] = encodeURI(arr[0]); + arr[2] = encodeURI(arr[2]); + return arr.join(''); + } else { + return encodeURI(uriStr); + } +} + +function createNewUri(uriStr) { + return new URI(uriStr); +} + +export default { + URI: URI, +} diff --git a/uri/tsconfig.json b/uri/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..66ad148561b08a71630eb07c7484394c2acc7930 --- /dev/null +++ b/uri/tsconfig.json @@ -0,0 +1,14 @@ +{ +"compilerOptions": { + "target": "es6", + "module": "es6", + "rootDir": "./src", + //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./out", /* Specify an output folder for all emitted files. */ + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "noImplicitThis": false, + } +} diff --git a/url/BUILD.gn b/url/BUILD.gn index 5e8d16faf82d5734f13bca03768b8c4aef43c0e1..72187427873ea7175b1439bdbab889b52f4beafb 100755 --- a/url/BUILD.gn +++ b/url/BUILD.gn @@ -11,14 +11,59 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") +import("//foundation/ace/ace_engine/ace_config.gni") +# compile .ts to .js. + +action("build_ts_js") { + script = "//base/compileruntime/js_api_module/url/build_ts_js.py" + depfile = "$target_gen_dir/$target_name.d" + outputs = [ target_out_dir + "/js_url.js" ] +} base_output_path = get_label_info(":js_url", "target_out_dir") js_url_obj_path = base_output_path + "/url.o" + gen_js_obj("js_url") { - input = "//base/compileruntime/js_api_module/url/js_url.js" + input = "$target_out_dir/js_url.js" output = js_url_obj_path + dep = ":build_ts_js" +} + +# compile .js to .abc. +action("gen_url_abc") { + visibility = [ ":*" ] + script = "//ark/ts2abc/ts2panda/scripts/generate_js_bytecode.py" + + args = [ + "--src-js", + rebase_path(target_out_dir + "/js_url.js"), + "--dst-file", + rebase_path(target_out_dir + "/url.abc"), + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + deps = [ + ":build_ts_js", + "//ark/ts2abc/ts2panda:ark_ts2abc_build", + ] + + inputs = [ target_out_dir + "/js_url.js" ] + outputs = [ target_out_dir + "/url.abc" ] +} + +abc_output_path = get_label_info(":url_abc", "target_out_dir") +url_abc_obj_path = abc_output_path + "/url_abc.o" +gen_js_obj("url_abc") { + input = "$target_out_dir/url.abc" + output = url_abc_obj_path + dep = ":gen_url_abc" } ohos_shared_library("url") { @@ -36,6 +81,7 @@ ohos_shared_library("url") { deps = [ ":js_url", + ":url_abc", "//base/compileruntime/js_api_module/url/:js_url", "//foundation/ace/napi/:ace_napi", "//foundation/ace/napi/:ace_napi_quickjs", diff --git a/url/build_ts_js.py b/url/build_ts_js.py new file mode 100755 index 0000000000000000000000000000000000000000..fb895e014581e8eac5f1948238fe4ea0af819d00 --- /dev/null +++ b/url/build_ts_js.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os + +if __name__ == '__main__': + + build_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) + os.chdir("%s/base/compileruntime/js_api_module/url" % build_path) + os.system('../../../../developtools/ace-ets2bundle/compiler/node_modules/typescript/bin/tsc') + + if os.access("../../../../out/ohos-arm64-release", os.F_OK): + os.system('cp -r ./out/js_url.js ../../../../out/ohos-arm64-release/obj/base/compileruntime/js_api_module/url/js_url.js') + + if os.access("../../../../out/ohos-arm-release", os.F_OK): + os.system('cp -r ./out/js_url.js ../../../../out/ohos-arm-release/obj/base/compileruntime/js_api_module/url/js_url.js') + + os.system('rm -rf ./out') \ No newline at end of file diff --git a/url/js_url.cpp b/url/js_url.cpp index ba9f1b93303998245c5fce2510b399e6e78a845f..6a2a4268bb9458177f6e4a8187d14fb6c5aa13fe 100755 --- a/url/js_url.cpp +++ b/url/js_url.cpp @@ -19,24 +19,24 @@ #include "securec.h" #include "utils/log.h" namespace OHOS::Url { - static std::map g_head = { + std::map g_head = { {"ftp:", 21}, {"file:", -1}, {"gopher:", 70}, {"http:", 80}, {"https:", 443}, {"ws:", 80}, {"wss:", 443} }; - static std::vector g_doubleSegment = { + std::vector g_doubleSegment = { "..", ".%2e", ".%2E", "%2e.", "%2E.", "%2e%2e", "%2E%2E", "%2e%2E", "%2E%2e" }; - static std::vector g_singlesegment = { ".", "%2e", "%2E" }; + std::vector g_singlesegment = { ".", "%2e", "%2E" }; - static std::vector g_specialcharacter = { + std::vector g_specialcharacter = { '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']' }; - static void ReplaceSpecialSymbols(std::string& input, std::string& oldstr, std::string& newstr) + void ReplaceSpecialSymbols(std::string& input, std::string& oldstr, std::string& newstr) { size_t oldlen = oldstr.size(); while (true) { @@ -64,7 +64,7 @@ namespace OHOS::Url { return false; } - static unsigned AsciiToHex(const unsigned char pram) + unsigned AsciiToHex(const unsigned char pram) { if (pram >= '0' && pram <= '9') { return pram - '0'; @@ -78,7 +78,7 @@ namespace OHOS::Url { return static_cast(-1); } - static std::string DecodePercent(const char *input, size_t len) + std::string DecodePercent(const char *input, size_t len) { std::string temp; if (len == 0) { @@ -106,7 +106,7 @@ namespace OHOS::Url { return temp; } - static void DeleteC0OrSpace(std::string& str) + void DeleteC0OrSpace(std::string& str) { if (str.empty()) { return; @@ -131,7 +131,7 @@ namespace OHOS::Url { } } - static void DeleteTabOrNewline(std::string& str1) + void DeleteTabOrNewline(std::string& str1) { for (auto item = str1.begin(); item != str1.end();) { if (IsASCIITabOrNewline(*item)) { @@ -142,7 +142,7 @@ namespace OHOS::Url { } } - static bool IsSpecial(std::string scheme) + bool IsSpecial(std::string scheme) { auto temp = g_head.count(scheme); if (temp > 0) { @@ -151,7 +151,7 @@ namespace OHOS::Url { return false; } - static bool AnalysisScheme(std::string& input, std::string& scheme, + bool AnalysisScheme(std::string& input, std::string& scheme, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { if (!isalpha(input[0])) { @@ -178,20 +178,20 @@ namespace OHOS::Url { } } - static void AnalysisFragment(const std::string& input, std::string& fragment, + void AnalysisFragment(const std::string& input, std::string& fragment, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { fragment = input; flags.set(static_cast(BitsetStatusFlag::BIT8)); } - static void AnalysisQuery(const std::string& input, std::string& query, + void AnalysisQuery(const std::string& input, std::string& query, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { query = input; flags.set(static_cast(BitsetStatusFlag::BIT7)); } - static void AnalysisUsernameAndPasswd(std::string& input, std::string& username, std::string& password, + void AnalysisUsernameAndPasswd(std::string& input, std::string& username, std::string& password, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { int pos = input.size() - 1; @@ -215,7 +215,6 @@ namespace OHOS::Url { } } } - if (userAndPasswd.find(':') != std::string::npos) { size_t i = userAndPasswd.find(':'); std::string user = userAndPasswd.substr(0, i); @@ -234,7 +233,7 @@ namespace OHOS::Url { } } - static void AnalysisPath(std::string& input, std::vector& path, + void AnalysisPath(std::string& input, std::vector& path, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, bool isSpecial) { std::vector temp; @@ -276,7 +275,7 @@ namespace OHOS::Url { } } - static void AnalysisPort(std::string input, UrlData& urlinfo, + void AnalysisPort(std::string input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { for (auto i : input) { @@ -302,7 +301,7 @@ namespace OHOS::Url { urlinfo.port = it; } - static void AnalysisOpaqueHost(std::string input, std::string& host, + void AnalysisOpaqueHost(std::string input, std::string& host, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { size_t strlen = input.size(); @@ -318,350 +317,329 @@ namespace OHOS::Url { flags.set(static_cast(BitsetStatusFlag::BIT4)); } - static std::string IPv6ZeroComperess(std::vector& tempIPV6, std::string& input, - int maxZeroIndex, int max) + std::string DealIpv4(std::string str) { - for (int i = 0; i < maxZeroIndex; ++i) { - input += tempIPV6[i]; - if (i != maxZeroIndex - 1) { - input += ":"; - } + std::vector temp; + size_t pos = str.rfind(":"); + size_t index = pos; + size_t left = pos + 1; + char hexVal[3] = { 0 }; + std::string val = ""; + while ((pos = str.find(".", left)) != std::string::npos) { + val = str.substr(left, pos - left); + snprintf(hexVal, sizeof(hexVal), "%02x", stoi(val)); + temp.push_back(hexVal); + left = pos + 1; + } + val = str.substr(left); + snprintf(hexVal, sizeof(hexVal), "%02x", stoi(val)); + temp.push_back(hexVal); + std::string res = str.substr(0, index); + res = res + ":" + temp[0] + temp[1] + ":" + temp[2] + temp[3]; + return res; + } + + std::string FormatIpv6(std::string ipv6String) + { + std::string str = ipv6String; + size_t pos = str.find("::"); + size_t index = pos; + if (pos == std::string::npos) { + return str; + } + size_t left = 0; + size_t count = 0; + while ((pos = str.find(":", left)) != std::string::npos) + { + count++; + left = pos + 1; + } + int size = 7 - (count - 2); // 7:point number 2:Continuous colon number + std::string temp = ""; + for (int i = 0; i < size - 1; ++i) { + temp += ":0"; } - input += "::"; - size_t strlen = tempIPV6.size(); - for (size_t i = maxZeroIndex + max; i < strlen; ++i) { - input += tempIPV6[i]; - if (i != strlen - 1) { - input += ":"; - } + temp += ":"; + str.replace(index, 2, temp); // 2:jump"::" + if (index == 0) { + str = "0" + str; } - return input; - } - - static std::string IPv6NoComperess(std::vector& tempIPV6, std::string& input) - { - size_t strlen = tempIPV6.size(); - for (size_t i = 0; i < strlen; ++i) { - if (tempIPV6[i][0] == '?' && tempIPV6[i].size() == 1) { - input += ":"; - } else { - input += tempIPV6[i]; - if (i != tempIPV6.size() - 1) { - input += ":"; - } - } - } - return input; + return str; } - static std::string IPv6HostCompress(std::vector& tempIPV6, int flag) + void RemoveLeadingZeros(std::vector &ipv6) { - std::string input; - if (flag == 1) { - return IPv6NoComperess(tempIPV6, input); - } - int max = 0; - int count = 0; - size_t maxZeroIndex = 0; - size_t strlen = tempIPV6.size(); - for (size_t i = 0; i < strlen;) { - if (tempIPV6[i] == "0" && (i + 1 < strlen && tempIPV6[i + 1] == "0")) { - int index = i; - while (i < strlen && tempIPV6[i] == "0") { - i++; - count++; - } - if (max < count) { - max = count; - maxZeroIndex = index; + size_t len = ipv6.size(); + for (size_t i = 0; i < len; ++i) { + size_t strLen = ipv6[i].size(); + size_t count = 0; + size_t j = 0; + for (j = 0; j < strLen; ++j) { + if (ipv6[i][j] != '0') { + break; } - } else { - count = 0; - i++; + count++; } - } - if (count == 8) { // 8:If IPv6 is all 0 - return "::"; - } else if (max == 0) { - strlen = tempIPV6.size(); - for (size_t i = 0; i < strlen; ++i) { - input += tempIPV6[i]; - if (i != strlen - 1) { - input += ":"; - } + if (count == strLen) { + ipv6[i] = "0"; } - return input; - } else if (maxZeroIndex == 0) { - input += "::"; - strlen = tempIPV6.size(); - for (size_t i = max; i < strlen; ++i) { - input += tempIPV6[i] + ":"; + else if (count != 0) { + ipv6[i] = ipv6[i].substr(j); } - input.pop_back(); - return input; - } else { - return IPv6ZeroComperess(tempIPV6, input, maxZeroIndex, max); } } - void DealWithtempIpv6(std::vector &tempIpv6, std::stringstream &ss, - std::string &numberHex, const int tempProt[4], int len) + std::string ZeroCompression(std::vector &ipv6) { - tempIpv6.push_back(numberHex); - ss.clear(); - numberHex.clear(); - if (len == 0) { - return; - } - ss << std::hex << tempProt[2] * 0x100 + tempProt[3]; // 2: 3:subscript position - ss >> numberHex; - tempIpv6.push_back(numberHex); - ss.clear(); - numberHex.clear(); - tempIpv6.erase(tempIpv6.end() - 3); // 3:Remove redundant space - } - - void IPv6DealWithColon(int& flag, std::string& strInput, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, size_t &pos) - { - flag = 1; - if (strInput.find("::", pos + 2) != std::string::npos) { // 2:Subscript Move Right2 - flags.set(static_cast(BitsetStatusFlag::BIT0)); - } - return; - } - - void IsFlagExist(size_t &pos, std::vector &temp, std::vector &tempEnd, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)> &flags, unsigned &numberFlag) - { - while (((pos = temp[numberFlag].find('.')) != std::string::npos)) { - tempEnd.push_back(temp[numberFlag].substr(0, pos)); - temp[numberFlag] = temp[numberFlag].substr(pos + 1); - } - tempEnd.push_back(temp[numberFlag]); - if (tempEnd.size() != 4) { // 4:The size is not 4 - flags.set(static_cast(BitsetStatusFlag::BIT0)); + size_t maxIndex = 0; + size_t maxSize = 0; + size_t index = 0; + size_t size = 0; + bool isNeedZeroCompression = false; + size_t len = ipv6.size(); + for (size_t i = 0; i < len; ++i) { + index = i; + size = 0; + while (i < len && ipv6[i] == "0") { + isNeedZeroCompression = true; + size++; + i++; + } + maxSize < size ? maxSize = size, maxIndex = index : 0; } - } - void DealWithProt(std::vector &tempEnd, unsigned &val, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, - int &number, int tempProt[4]) - { - size_t strlen = tempEnd.size(); - for (size_t x = 0; x < strlen; ++x) { - val = stoi(tempEnd[x]); - if (val > 255) { // 255:The maximum value is 255 - flags.set(static_cast(BitsetStatusFlag::BIT0)); - return; + std::string res = ""; + size_t ipv6Len = ipv6.size(); + for (size_t i = 0; i < ipv6Len; ++i) { + if (isNeedZeroCompression && i == maxIndex) { + maxIndex == 0 ? res += "::" : res += ":"; + i += maxSize - 1; + continue; } - tempProt[number] = val; - number++; - val = 0; + res += ipv6[i]; + i != (ipv6Len - 1) ? res += ":" : ""; } + return res; } - void DealWithElse(std::vector &temp, size_t &i, unsigned &numberFlag, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, unsigned &val) + void ToLower(std::string &str) { - size_t strlen = temp[i].size(); - for (size_t j = 0; j < strlen; ++j) { - if (((temp[i].find('.')) != std::string::npos)) { - numberFlag = i; - if (temp.size() == i || temp.size() > 7) { // 7:The size cannot be greater than 7 - flags.set(static_cast(BitsetStatusFlag::BIT0)); - return; - } - return; - } else if (IsHexDigit(temp[i][j])) { - val = val * 0x10 + AsciiToHex(temp[i][j]); + size_t strLen = str.size(); + for (size_t i = 0; i < strLen; ++i) { + if (isupper(str[i])) { + str[i] = tolower(str[i]); } } } - void DealWithStringStream(std::stringstream &ss, unsigned &val, - std::string &numberHex, std::vector &tempIpv6) + std::string Compress(std::string str) { - ss << std::hex << val; - ss >> numberHex; - tempIpv6.push_back(numberHex); - ss.clear(); - numberHex.clear(); - val = 0; + std::vector temp; + size_t pos = 0; + size_t left = 0; + while ((pos = str.find(":", left)) != std::string::npos) { + temp.push_back(str.substr(left, pos - left)); + left = pos + 1; + } + temp.push_back(str.substr(left)); + RemoveLeadingZeros(temp); + std::string res = ZeroCompression(temp); + ToLower(res); + return res; } - static void IPv6Host(std::string& input, std::string& host, + void IPv6Host(std::string& input, std::string& host, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { - if (input.size() == 0) { + std::regex ipv6("(::|(:((:[0-9A-Fa-f]{1,4}){1,7}))|(([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|" + "(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|:))|(([0-9A-Fa-f]{1,4}:){2}" + "(((:[0-9A-Fa-f]{1,4}){1,5})|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})" + "|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|:))|(([0-9A-Fa-f]{1,4}:){5}" + "(((:[0-9A-Fa-f]{1,4}){1,2})|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|:))|" + "(((:(:[0-9A-Fa-f]{1,4}){0,5}:)|(([0-9A-Fa-f]{1,4}:){1}(:[0-9A-Fa-f]{1,4}){0,4}:)" + "|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}:)|(([0-9A-Fa-f]{1,4}:){3}" + "(:[0-9A-Fa-f]{1,4}){0,2}:)|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4})?:)|" + "(([0-9A-Fa-f]{1,4}:){5}:)|(([0-9A-Fa-f]{1,4}:){6}))((25[0-5]|2[0-4]\\d|1\\d{2}|" + "[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)))(%[a-zA-Z0-9._]+)?"); + if (!std::regex_match(input, ipv6)) { flags.set(static_cast(BitsetStatusFlag::BIT0)); return; } - std::string strInput = input; - std::stringstream ss; - std::string numberHex; - unsigned val = 0; - unsigned numberFlag = 0; - std::vector temp; - std::vector tempEnd; - std::vector tempIpv6; size_t pos = 0; - int tempProt[4] = { 0 }; - int number = 0; - int flag = 0; - if ((pos = strInput.find("::", 0)) != std::string::npos) { - IPv6DealWithColon(flag, strInput, flags, pos); - } - while (((pos = strInput.find(':')) != std::string::npos)) { - temp.push_back(strInput.substr(0, pos)); - strInput = strInput.substr(pos + 1); - } - temp.push_back(strInput); - if (temp.size() > 8) { // 8:The incoming value does not meet the criteria - flags.set(static_cast(BitsetStatusFlag::BIT0)); - return; - } - size_t length = temp.size(); - for (size_t i = 0; i < length; ++i) { - if (temp[i].empty()) { - tempIpv6.push_back("?"); - } else { - DealWithElse(temp, i, numberFlag, flags, val); - DealWithStringStream(ss, val, numberHex, tempIpv6); - } - } - if (numberFlag != 0) { - IsFlagExist(pos, temp, tempEnd, flags, numberFlag); - DealWithProt(tempEnd, val, flags, number, tempProt); - ss << std::hex << tempProt[0] * 0x100 + tempProt[1]; - ss >> numberHex; - DealWithtempIpv6(tempIpv6, ss, numberHex, tempProt, 4); // 4:tempProtlen + pos = input.find('.'); + if (pos != std::string::npos) { + input = DealIpv4(input); } - strInput = IPv6HostCompress(tempIpv6, flag); - host = '[' + strInput + ']'; + input = FormatIpv6(input); + input = Compress(input); + host = "[" + input + "]"; flags.set(static_cast(BitsetStatusFlag::BIT4)); flags.set(static_cast(BitsetStatusFlag::BIT10)); } - static bool CheckNunType(const char ch, const unsigned num) - { - enum class NUMERATION { - OCT = 8, // 8:Octal - DEC = 10, // 10:Decimal - HEX = 16 // 16:Hexadecimal - }; - if (NUMERATION(num) == NUMERATION::OCT) { - if (ch < '0' || ch > '7') { // 0~7:Octal - return false; - } - } else if (NUMERATION(num) == NUMERATION::DEC) { - if (ch < '0' || ch > '9') { // 0~9:Decimal - return false; - } - } else if (NUMERATION(num) == NUMERATION::HEX) { - if (!((ch >= '0' && ch <= '9') || // 0~9, a~f, A~F:Hexadecimal - (ch >= 'A' && ch <= 'F') || - (ch >= 'a' && ch <= 'f'))) { + bool IsRadix(std::string num, std::string radix) { + size_t len = num.size(); + for (size_t i = 0; i < len; ++i) { + if (radix.find(num[i]) == std::string::npos) { return false; } } return true; } - static int64_t AnalyseNum(std::string parts) + bool IsNumber(std::string num, int &radix) { - unsigned num = 10; // 10:Decimal - std::string partsBeg = parts.substr(0, 2); // 2:Take two digits to determine whether it is hexadecimal - size_t partsLen = parts.length(); - if (partsLen >= 2 && (partsBeg == "0X" || partsBeg == "0x")) { // 2:parts length - num = 16; // 16:Convert to hexadecimal - parts = parts.substr(2); // 2:delete '0x' - } else if (num == 10 && partsLen > 1 && parts.substr(0, 1) == "0") { // 10:Conversion to Decimal Coefficient - num = 8; // 8:Convert to octal - parts = parts.substr(1); - } - for (size_t i = 0; i < parts.length(); i++) { - bool ret = CheckNunType(parts[i], num); - if (!ret) { - return -1; - } + size_t len = num.size(); + if (len > 2 && num[0] == '0' && (num[1] == 'x' || num[1] == 'X')) { // 2:hex head length + radix = 16; // 16:hex + return IsRadix(num.substr(2), "0123456789abcdefABCDEF"); // 2:jump 0x + } else if (len > 1 && num[0] == '0') { + radix = 8; // 8:octal + return IsRadix(num.substr(1), "01234567"); + } else if (IsRadix(num, "0123456789")) { + radix = 10; // 10:decimal + return true; } - return strtoll(parts.c_str(), nullptr, num); + return false; } - static bool OverHex(std::string input) + std::string BinaryConversion(std::string num, int radix) { - size_t size = input.size(); - for (size_t i = 0; i < size; i++) { - return !IsHexDigit(input[i]); + int val = 0; + if (radix == 16) { // 16:hex + sscanf_s(num.c_str(),"%x", &val); + return std::to_string(val); + } else if (radix == 8) { // 8:octal + sscanf_s(num.c_str(), "%o", &val); + return std::to_string(val); + } else { + return num; } - return false; } - static bool NotAllNum(std::string input) + bool RemovalIpv4(std::vector &temp, std::string str) { - size_t size = input.size(); - for (size_t i = 0; i < size; i++) { - if (!isdigit(input[i])) { - return true; + size_t pos = 0; + size_t left = 0; + while ((pos = str.find(".", left)) != std::string::npos) { + temp.push_back(str.substr(left, pos - left)); + left = pos + 1; + } + temp.push_back(str.substr(left)); + size_t tmpLen = temp.size(); + std::vector res; + for (size_t i = 0; i < tmpLen; ++i) { + int radix = 0; + if (IsNumber(temp[i], radix)) { + res.push_back(BinaryConversion(temp[i], radix)); + } else { + return false; } } - return false; + temp = res; + return true; } - static bool AnalyseIPv4(const char *instr, std::string &host, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)> &flags) + int IsFormatIpv4(std::vector nums) { - int count = 0; - for (const char *ptr = instr; *ptr != '\0'; ptr++) { - if (*ptr == '.') { - if (++count > 3) { // 3:The IPV4 address has only four segments - return false; - } + size_t len = nums.size(); + for (size_t i = 0; i < len; ++i) { + if (stoi(nums[i]) > 255) { // 255:ipv4 max value + return i; } } - if (count != 3) { // 3:The IPV4 address has only four segments - return false; - } + return -1; + } - size_t pos = 0; - std::vector strVec; - std::string input = static_cast(instr); - while (((pos = input.find('.')) != std::string::npos)) { - strVec.push_back(input.substr(0, pos)); - input = input.substr(pos + 1); + std::string SplitNum(std::string num, size_t &number) + { + int val = stoi(num); + std::vector nums; + std::string res = ""; + while (val > 0) { + int num = val % 256; // 256:ipv4 max value + nums.push_back(std::to_string(num)); + val /= 256; // 256:ipv4 max value } - strVec.push_back(input); - size_t size = strVec.size(); - for (size_t i = 0; i < size; i++) { - if (strVec[i].empty()) { - return false; - } - std::string begStr = strVec[i].substr(0, 2); // 2:Intercept the first two characters - if ((begStr == "0x" || begStr == "0X") && OverHex(strVec[i].substr(2))) { // 2:Intercept - return false; - } else if ((begStr == "0x" || begStr == "0X") && !(OverHex(strVec[i].substr(2)))) { // 2:Intercept - continue; + for (int i = nums.size() - 1; i >= 0; --i) { + res += nums[i] + "."; + } + number = nums.size(); + return res.substr(0, res.size() - 1); + } + + void FormatIpv4(std::vector nums, std::string& host, + std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) + { + size_t len = nums.size(); + int index = IsFormatIpv4(nums); + std::string res = ""; + if (index == -1) { + for (size_t i = 0; i < len - 1; ++i) { + res += nums[i] + "."; + } + for (size_t i = 0; i < 4 - len; ++i) { // 4:ipv4 max size + res += "0."; + } + res += nums[len - 1]; + host = res; + flags.set(static_cast(BitsetStatusFlag::BIT4)); + } else if (index == static_cast(len - 1)) { + for (size_t i = 0; i < len - 1; ++i) { + res += nums[i] + "."; + } + size_t number = 0; + std::string temp = SplitNum(nums[index], number); + if (number + (len - 1) > 4) { // 4:ipv4 max size + flags.set(static_cast(BitsetStatusFlag::BIT0)); + return; } - if (NotAllNum(strVec[i])) { - return false; + for (size_t i = 0; i < 4 - (len - 1 + number); ++i) { // 4:ipv4 max size + temp = "0." + temp; } + host = res + temp; + flags.set(static_cast(BitsetStatusFlag::BIT4)); + } else { + flags.set(static_cast(BitsetStatusFlag::BIT0)); + return; } - for (size_t i = 0; i < size; i++) { - int64_t value = AnalyseNum(strVec[i].c_str()); - if ((value < 0) || (value > 255)) { // 255:Only handle numbers between 0 and 255 - flags.set(static_cast(BitsetStatusFlag::BIT0)); - return false; - } else { - host += std::to_string(value); - if (i != size - 1) { - host += "."; + + } + void AnalyseIPv4(const std::string input, std::string& host, + std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) + { + bool isipv4 = false; + std::vector temp; + isipv4 = RemovalIpv4(temp, input); + size_t tempLen = temp.size(); + std::string res = ""; + for (size_t i = 0; i < tempLen; ++i) { + res += temp[i]; + if (i != tempLen - 1) { + res += "."; + } + } + if (isipv4) { + if (tempLen > 4) { // 4:ipv4 max size + ToLower(res); + host = res; + flags.set(static_cast(BitsetStatusFlag::BIT4)); + } else if (tempLen == 4) { // 4:ipv4 max size + if (IsFormatIpv4(temp) == -1) { + host = res; + flags.set(static_cast(BitsetStatusFlag::BIT4)); + } else { + flags.set(static_cast(BitsetStatusFlag::BIT0)); } + } else { + FormatIpv4(temp, host, flags); } + } else { + ToLower(res); + host = res; + flags.set(static_cast(BitsetStatusFlag::BIT4)); } - flags.set(static_cast(BitsetStatusFlag::BIT4)); - return true; } - static void AnalysisHost(std::string& input, std::string& host, + void AnalysisHost(std::string& input, std::string& host, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, bool special) { if (input.empty()) { @@ -693,21 +671,16 @@ namespace OHOS::Url { return; } } - bool ipv4 = AnalyseIPv4(decodeInput.c_str(), host, flags); - if (ipv4) { - return; - } - host = decodeInput; - flags.set(static_cast(BitsetStatusFlag::BIT4)); + AnalyseIPv4(decodeInput, host, flags); } - static bool ISFileNohost(const std::string& input) + bool ISFileNohost(const std::string& input) { if ((isalpha(input[0]) && (input[1] == ':' || input[1] == '|'))) { return true; } return false; } - static void AnalysisFilePath(std::string& input, UrlData& urlinfo, + void AnalysisFilePath(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { std::vector temp; @@ -752,7 +725,7 @@ namespace OHOS::Url { } } - static void AnalysisFile(std::string& input, UrlData& urlinfo, + void AnalysisFile(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { bool special = true; @@ -793,7 +766,7 @@ namespace OHOS::Url { } } - static void AnalysisFilescheme(std::string& input, UrlData& urlinfo, + void AnalysisFilescheme(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { std::string strPath = urlinfo.scheme + input; @@ -839,7 +812,7 @@ namespace OHOS::Url { } } - static void AnalysisNoDefaultProtocol(std::string& input, UrlData& urlinfo, + void AnalysisNoDefaultProtocol(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { if (urlinfo.scheme.size() == 2) { // 2:The length is 2 @@ -890,7 +863,7 @@ namespace OHOS::Url { } } - static void AnalysisOnlyHost(std::string& input, UrlData& urlinfo, + void AnalysisOnlyHost(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, size_t pos) { std::string strHost = input; @@ -922,7 +895,7 @@ namespace OHOS::Url { } } } - static void AnalysisHostAndPath(std::string& input, UrlData& urlinfo, + void AnalysisHostAndPath(std::string& input, UrlData& urlinfo, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { if (flags.test(static_cast(BitsetStatusFlag::BIT1))) { @@ -973,7 +946,7 @@ namespace OHOS::Url { } } - static void AnalysisInput(std::string& input, UrlData& urlData, + void AnalysisInput(std::string& input, UrlData& urlData, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) { if (input.find('#') != std::string::npos) { @@ -992,7 +965,7 @@ namespace OHOS::Url { AnalysisPath(input, urlData.path, flags, special); } - static void BaseInfoToUrl(const UrlData& baseInfo, + void BaseInfoToUrl(const UrlData& baseInfo, const std::bitset(BitsetStatusFlag::BIT_STATUS_11)> baseflags, UrlData& urlData, std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags, bool inputIsEmpty) { @@ -1027,7 +1000,7 @@ namespace OHOS::Url { baseflags.test(static_cast(BitsetStatusFlag::BIT10))); } - static void ShorteningPath(UrlData& baseData, bool isFile) + void ShorteningPath(UrlData& baseData, bool isFile) { if (baseData.path.empty()) { return; @@ -1039,6 +1012,44 @@ namespace OHOS::Url { baseData.path.pop_back(); } + void InitOnlyInput(std::string& input, UrlData& urlData, + std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) + { + if (input.empty()) { + flags.set(static_cast(BitsetStatusFlag::BIT0)); + return; + } + if (input.find(':') != std::string::npos) { + size_t pos = input.find(':'); + pos++; + std::string scheme = input.substr(0, pos); + if (!AnalysisScheme(scheme, urlData.scheme, flags)) { + return; + } + if (input.find('#') != std::string::npos) { + size_t i = input.find('#'); + std::string fragment = input.substr(i); + AnalysisFragment(fragment, urlData.fragment, flags); + input = input.substr(0, i); + } + if (input.find('?') != std::string::npos) { + size_t i = input.find('?'); + std::string query = input.substr(i); + AnalysisQuery(query, urlData.query, flags); + input = input.substr(0, i); + } + std::string str = input.substr(pos); + if (urlData.scheme == "file:") { + AnalysisFile(str, urlData, flags); + } else { + AnalysisHostAndPath(str, urlData, flags); + } + } else { + flags.set(static_cast(BitsetStatusFlag::BIT0)); + return; + } + } + URL::URL(napi_env env, const std::string& input) { env_ = env; @@ -1055,7 +1066,7 @@ namespace OHOS::Url { DeleteTabOrNewline(strBase); DeleteC0OrSpace(strInput); DeleteTabOrNewline(strInput); - URL::InitOnlyInput(strBase, baseInfo, baseflags); + InitOnlyInput(strBase, baseInfo, baseflags); } URL::URL(napi_env env, const std::string& input, const std::string& base) @@ -1591,44 +1602,6 @@ namespace OHOS::Url { } } - void URL::InitOnlyInput(std::string& input, UrlData& urlData, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags) - { - if (input.empty()) { - flags.set(static_cast(BitsetStatusFlag::BIT0)); - return; - } - if (input.find(':') != std::string::npos) { - size_t pos = input.find(':'); - pos++; - std::string scheme = input.substr(0, pos); - if (!AnalysisScheme(scheme, urlData.scheme, flags)) { - return; - } - if (input.find('#') != std::string::npos) { - size_t i = input.find('#'); - std::string fragment = input.substr(i); - AnalysisFragment(fragment, urlData.fragment, flags); - input = input.substr(0, i); - } - if (input.find('?') != std::string::npos) { - size_t i = input.find('?'); - std::string query = input.substr(i); - AnalysisQuery(query, urlData.query, flags); - input = input.substr(0, i); - } - std::string str = input.substr(pos); - if (urlData.scheme == "file:") { - AnalysisFile(str, urlData, flags); - } else { - AnalysisHostAndPath(str, urlData, flags); - } - } else { - flags.set(static_cast(BitsetStatusFlag::BIT0)); - return; - } - } - URLSearchParams::URLSearchParams(napi_env env) : env(env) {} std::wstring StrToWstr(const std::string& str) @@ -1705,7 +1678,7 @@ namespace OHOS::Url { (charaEncode & 0x0000003F)]; // Acquisition method of the second byte output += output1 + output2; } else if ((charaEncode >= 0x0000E000) || - (charaEncode <= 0x0000D7FF)) { // Convert the Unicode code into three bytes + (charaEncode <= 0x0000D7FF)) { // Convert the Unicode code into three bytes std::string output1 = reviseChar[0x000000E0 | (charaEncode / 4096)]; // 4096:Acquisition method of the first byte std::string output2 = reviseChar[numOfAscii | @@ -1935,7 +1908,7 @@ namespace OHOS::Url { sname = ToUSVString(name); } delete[] name; - for (std::vector::iterator iter = searchParams.begin(); iter != searchParams.end();) { + for (auto iter = searchParams.begin(); iter != searchParams.end();) { if (*iter == sname) { iter = searchParams.erase(iter, iter + 2); // 2:Searching for the number and number of keys and values } else { @@ -2032,7 +2005,7 @@ namespace OHOS::Url { delete[] buffer1; } bool flag = false; - for (std::vector::iterator it = searchParams.begin(); it < searchParams.end() - 1;) { + for (auto it = searchParams.begin(); it < (searchParams.end() - 1);) { if (*it == cppName) { if (!flag) { *(it + 1) = cppValue; diff --git a/url/js_url.h b/url/js_url.h index ac55ff4413e4fa10389dbea78823cf025e45e878..9a9e1ff9ef49c48f5f8bf183c0870be60beba51c 100755 --- a/url/js_url.h +++ b/url/js_url.h @@ -81,8 +81,6 @@ namespace OHOS::Url { napi_value GetIsIpv6() const; napi_value GetHost() const; - static void InitOnlyInput(std::string& input, UrlData& urlData, - std::bitset(BitsetStatusFlag::BIT_STATUS_11)>& flags); virtual ~URL() {} private: UrlData urlData_; diff --git a/url/native_module_url.cpp b/url/native_module_url.cpp index 279f4316738e6d8449c3ebcb9578845a00c8589c..75cf918a592962293553f7e86cdacb7d40030e5e 100755 --- a/url/native_module_url.cpp +++ b/url/native_module_url.cpp @@ -20,6 +20,8 @@ extern const char _binary_js_url_js_start[]; extern const char _binary_js_url_js_end[]; +extern const char _binary_url_abc_start[]; +extern const char _binary_url_abc_end[]; namespace OHOS::Url { static void UrlStructor(napi_env &env, napi_callback_info &info, URL *&object) { @@ -58,7 +60,7 @@ namespace OHOS::Url { object = new URL(env, input, base); } else if (valuetype2 == napi_object) { URL *temp = nullptr; - napi_unwrap(env, argv[1], (void**)&temp); + napi_unwrap(env, argv[1], reinterpret_cast(&temp)); object = new URL(env, input, *temp); } else { HILOG_INFO("secondParameter error"); @@ -116,7 +118,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetHostname(); return retVal; } @@ -126,7 +128,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetSearch(); return retVal; } @@ -136,7 +138,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetUsername(); return retVal; } @@ -146,7 +148,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetPassword(); return retVal; } @@ -156,7 +158,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetFragment(); return retVal; } @@ -166,7 +168,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetScheme(); return retVal; } @@ -176,7 +178,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetPort(); return retVal; } @@ -186,7 +188,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetHost(); return retVal; } @@ -196,7 +198,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetPath(); return retVal; } @@ -206,7 +208,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetOnOrOff(); return retVal; } @@ -216,7 +218,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetIsIpv6(); return retVal; } @@ -241,7 +243,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetHref(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -268,7 +270,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetHostname(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -295,7 +297,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetPort(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -322,7 +324,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetHost(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -349,7 +351,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetSearch(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -376,7 +378,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetScheme(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -403,7 +405,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetFragment(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -430,7 +432,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetUsername(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -457,7 +459,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetPath(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -484,7 +486,7 @@ namespace OHOS::Url { type = nullptr; } URL *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetPassword(input); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -535,7 +537,7 @@ namespace OHOS::Url { } } URLSearchParams *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); murl->SetArray(vec); napi_value result = nullptr; NAPI_CALL(env, napi_get_undefined(env, &result)); @@ -547,7 +549,7 @@ namespace OHOS::Url { napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); URLSearchParams *murl = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&murl)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&murl))); napi_value retVal = murl->GetArray(); return retVal; } @@ -563,7 +565,7 @@ namespace OHOS::Url { return nullptr; } URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); napi_value result = object->Get(args); return result; } @@ -579,7 +581,7 @@ namespace OHOS::Url { return nullptr; } URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); napi_value result = object->GetAll(args); return result; } @@ -596,7 +598,7 @@ namespace OHOS::Url { return nullptr; } URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); object->Append(args[0], args[1]); return nullptr; } @@ -612,7 +614,7 @@ namespace OHOS::Url { return nullptr; } URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); object->Delete(args); return nullptr; } @@ -624,7 +626,7 @@ namespace OHOS::Url { napi_value args = nullptr; napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr); URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); object->ForEach(args, thisVar); return nullptr; } @@ -636,7 +638,7 @@ namespace OHOS::Url { napi_value args = nullptr; napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr); URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); napi_value result = object->Entries(); return result; } @@ -648,7 +650,7 @@ namespace OHOS::Url { napi_value args = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr)); URLSearchParams *object = nullptr; - NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&object)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&object))); napi_value result = object->IsHas(args); return result; } @@ -660,7 +662,7 @@ namespace OHOS::Url { napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); object->Set(args[0], args[1]); return nullptr; } @@ -672,7 +674,7 @@ namespace OHOS::Url { napi_value args = nullptr; napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr); URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); object->Sort(); return nullptr; } @@ -684,7 +686,7 @@ namespace OHOS::Url { napi_value args = nullptr; napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr); URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); napi_value result = object->ToString(); return result; } @@ -696,7 +698,7 @@ namespace OHOS::Url { napi_value args = nullptr; napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr); URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); napi_value result = object->IterByKeys(); return result; } @@ -708,7 +710,7 @@ namespace OHOS::Url { napi_value args = nullptr; napi_get_cb_info(env, info, &argc, &args, &thisVar, nullptr); URLSearchParams *object = nullptr; - napi_unwrap(env, thisVar, (void**)&object); + napi_unwrap(env, thisVar, reinterpret_cast(&object)); napi_value result = object->IterByValues(); return result; } @@ -884,7 +886,7 @@ namespace OHOS::Url { DECLARE_NAPI_GETTER("GetIsIpv6", GetIsIpv6), }; NAPI_CALL(env, napi_define_class(env, urlClassName, strlen(urlClassName), UrlConstructor, - nullptr, sizeof(UrlDesc) / sizeof(UrlDesc[0]), UrlDesc, &urlClass)); + nullptr, sizeof(UrlDesc) / sizeof(UrlDesc[0]), UrlDesc, &urlClass)); static napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("Url", urlClass) }; @@ -914,7 +916,16 @@ namespace OHOS::Url { *bufLen = _binary_js_url_js_end - _binary_js_url_js_start; } } - + extern "C" + __attribute__((visibility("default"))) void NAPI_url_GetABCCode(const char** buf, int* buflen) + { + if (buf != nullptr) { + *buf = _binary_url_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_url_abc_end - _binary_url_abc_start; + } + } static napi_module UrlModule = { .nm_version = 1, .nm_flags = 0, diff --git a/url/js_url.js b/url/src/js_url.ts old mode 100755 new mode 100644 similarity index 82% rename from url/js_url.js rename to url/src/js_url.ts index 7eef1b4c43b8ffd514dd0fea8fbdbe789660c41e..aae31cf4459ab5329a42f9043bc2830f97f4aa9c --- a/url/js_url.js +++ b/url/src/js_url.ts @@ -1,416 +1,420 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; -const Url = requireInternal("url"); - -let seachParamsArr = []; -class URLSearchParams { - urlcalss; - constructor(input) { - let out = []; - out = parameterProcessing(input); - this.urlcalss = new Url.URLSearchParams1(); - this.urlcalss.array = out; - } - append(params1, params2) { - this.urlcalss.append(params1, params2); - } - - set(setname, setvalues) { - this.urlcalss.set(setname, setvalues); - } - - sort() { - this.urlcalss.sort(); - } - - has(hasname) { - return this.urlcalss.has(hasname); - } - toString() { - return this.urlcalss.toString(); - } - - keys() { - return this.urlcalss.keys(); - } - - values() { - console.log('constructor failed'); - return this.urlcalss.values(); - } - - getAll(getAllname) { - return this.urlcalss.getAll(getAllname); - } - - get(getname) { - return this.urlcalss.get(getname); - } - - entries() { - - return this.urlcalss.entries(); - } - - delete(deletename) { - this.urlcalss.delete(deletename); - } - - forEach(objfun) { - return this.urlcalss.forEach(objfun); - } - - [Symbol.iterator]() { - return this.urlcalss.entries(); - } - - updateParams(input) { - let out = []; - out = parameterProcessing(input); - this.urlcalss.array = out; - } -} - -function toHleString(arg) { - return arg.toString(); -} - -function parameterProcessing(input) { - if (input === null || typeof input === 'undefined') { - seachParamsArr = []; - return seachParamsArr; - } else if (typeof input === 'object' || typeof input === 'function') { - return initObjectSeachParams(input); - } else { - return initToStringSeachParams(input); - } -} -function initObjectSeachParams(input) { - if (typeof input[Symbol.iterator] === 'function') { - return iteratorMethod(input); - } - return recordMethod(input); -} -function recordMethod(input) { - const objectkeys = Reflect.ownKeys(input); - seachParamsArr = []; - let objectlength = objectkeys.length; - for (let i = 0; i <= objectlength; i++) { - const objectkey = objectkeys[i]; - const descry = Reflect.getOwnPropertyDescriptor(input, objectkey); - if (descry !== undefined && descry.enumerable) { - const inputkey = toHleString(objectkey); - const inputValue = toHleString(input[objectkey]); - seachParamsArr.push(inputkey, inputValue); - } - } - return seachParamsArr; -} -function iteratorMethod(input) { - let pairs = []; - seachParamsArr = []; - for (const pair of input) { - const conversionsPair = []; - for (let element of pair) { - conversionsPair.push(element); - } - pairs.push(conversionsPair); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - console.log('key-value-is-worong'); - } - seachParamsArr.push(pair[0], pair[1]); - } - return seachParamsArr; -} - -function initToStringSeachParams(input) { - if (input[0] === '?') { - input = input.slice(1); - } - let strVal = decodeURI(input); - seachParamsArr = Url.stringParmas(strVal); - return seachParamsArr; -} -class URL { - href_; - search_; - origin_; - username_; - password_; - hostname_; - host_; - hash_; - protocol_; - pathname_; - port_; - searchParamsClass_; - c_info; - constructor() { - let nativeUrl; - let inputUrl; - let inputBase; - - if (arguments.length === 1) { - inputUrl = arguments[0]; - if (typeof inputUrl === 'string' && inputUrl.length > 0) { - nativeUrl = new Url.Url(inputUrl); - } else { - console.log('Input parameter error'); - } - } - - if (arguments.length === 2) { - inputUrl = arguments[0]; - inputBase = arguments[1]; - if (typeof inputUrl === 'string') { - if (typeof inputBase === 'string') { - if (inputBase.length > 0) { - nativeUrl = new Url.Url(inputUrl, inputBase); - } else { - console.log('Input parameter error'); - return; - } - } - if (typeof inputBase === 'object') { - let nativeBase = inputBase.getInfo(); - nativeUrl = new Url.Url(inputUrl, nativeBase); - } - } - } - this.c_info = nativeUrl; - if (nativeUrl.onOrOff) { - this.search_ = encodeURI(nativeUrl.search); - this.username_ = encodeURI(nativeUrl.username); - this.password_ = encodeURI(nativeUrl.password); - if (nativeUrl.GetIsIpv6) { - this.hostname_ = nativeUrl.hostname; - this.host_ = nativeUrl.host; - } else { - this.hostname_ = encodeURI(nativeUrl.hostname); - this.host_ = encodeURI(nativeUrl.host); - } - this.hash_ = encodeURI(nativeUrl.hash); - this.protocol_ = encodeURI(nativeUrl.protocol); - this.pathname_ = encodeURI(nativeUrl.pathname); - this.port_ = nativeUrl.port; - this.origin_ = nativeUrl.protocol + '//' + nativeUrl.host; - this.searchParamsClass_ = new URLSearchParams(this.search_); - this.set_href(); - } else { - console.log('constructor failed'); - } - } - getInfo() { - return this.c_info; - } - toString() { - return this.href_; - } - - get protocol() { - return this.protocol_; - } - set protocol(scheme) { - if (scheme.length === 0) { - return; - } - if (this.protocol_ === 'file:' - && (this.host_ === '' || this.host_ == null)) { - return; - } - this.c_info.protocol = scheme; - this.protocol_ = this.c_info.protocol; - this.set_href() - } - get origin() { - let kOpaqueOrigin = 'null'; - switch (this.protocol_) { - case 'ftp:': - case 'gopher:': - case 'http:': - case 'https:': - case 'ws:': - case 'wss:': - return this.origin_; - } - return kOpaqueOrigin; - } - get username() { - return this.username_; - } - set username(input) { - if (this.host_ == null || this.host_ === '' || this.protocol_ === 'file:') { - return; - } - const usname_ = escape(input); - this.c_info.username = usname_; - this.username_ = this.c_info.username; - this.set_href(); - } - get password() { - return this.password_; - } - set password(input) { - if (this.host_ == null || this.host_ === '' || this.protocol_ === 'file:') { - return; - } - const passwd_ = escape(input); - this.c_info.password = passwd_; - this.password_ = this.c_info.password; - this.set_href(); - } - get hash() { - return this.hash_; - } - set hash(fragment) { - const fragment_ = encodeURI(fragment); - this.c_info.hash = fragment_; - this.hash_ = this.c_info.hash; - this.set_href(); - } - get search() { - return this.search_; - } - set search(query) { - const query_ = encodeURI(query); - this.c_info.search = query_; - this.search_ = this.c_info.search; - this.searchParamsClass_.updateParams(this.search_); - this.set_href(); - } - get hostname() { - return this.hostname_; - } - set hostname(hostname) { - this.c_info.hostname = hostname; - if (this.c_info.GetIsIpv6) { - this.hostname_ = this.c_info.hostname; - } else { - this.hostname_ = encodeURI(this.c_info.hostname); - } - this.set_href(); - } - get host() { - return this.host_; - } - set host(host_) { - this.c_info.host = host_; - if (this.c_info.GetIsIpv6) { - this.host_ = this.c_info.host; - this.hostname_ = this.c_info.hostname; - this.port_ = this.c_info.port; - } else { - this.host_ = encodeURI(this.c_info.host); - this.hostname_ = encodeURI(this.c_info.hostname); - this.port_ = this.c_info.port; - } - this.set_href(); - } - get port() { - return this.port_; - } - set port(port) { - if (this.host_ === '' || this.protocol_ === 'file:' || port === '') { - return; - } - this.c_info.port = port; - this.port_ = this.c_info.port; - this.set_href(); - } - get href() { - return this.href_; - } - set href(href_) { - this.c_info.href(href_); - if (this.c_info.onOrOff) { - this.search_ = encodeURI(this.c_info.search); - this.username_ = encodeURI(this.c_info.username); - this.password_ = encodeURI(this.c_info.password); - if (this.c_info.GetIsIpv6) { - this.hostname_ = this.c_info.hostname; - this.host_ = this.c_info.host; - } else { - this.hostname_ = encodeURI(this.c_info.hostname); - this.host_ = encodeURI(this.c_info.host); - } - this.hash_ = encodeURI(this.c_info.hash); - this.protocol_ = encodeURI(this.c_info.protocol); - this.pathname_ = encodeURI(this.c_info.pathname); - this.port_ = this.c_info.port; - this.origin_ = this.protocol_ + '//' + this.host_; - this.searchParamsClass_.updateParams(this.search_); - this.set_href(); - } - } - - get pathname() { - return this.pathname_; - } - set pathname(path) { - const path_ = encodeURI(path); - this.c_info.pathname = path_; - this.pathname_ = this.c_info.pathname; - this.set_href(); - } - - get searchParams() { - return this.searchParamsClass_; - } - - toJSON() { - return this.href_; - } - set_href() { - let temp = this.protocol_; - if (this.hostname_ !== '') { - temp += '//'; - if (this.password_ !== '' || this.username_ !== '') { - if (this.username_ !== '') { - temp += this.username_; - } - if (this.password_ !== '') { - temp += ':'; - temp += this.password_; - } - temp += '@'; - } - temp += this.hostname_; - if (this.port_ !== '') { - temp += ':'; - temp += this.port_; - } - } else if (this.protocol_ === 'file:') { - temp += '//'; - } - temp += this.pathname_; - if (this.search_) { - temp += this.search_; - } - if (this.hash_) { - temp += this.hash_; - } - this.href_ = temp; - } -} - -export default { - URLSearchParams: URLSearchParams, - URL: URL, -} +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare function requireInternal(s : string) : any; +const urlUtil = requireInternal('url'); + +let seachParamsArr:Array = []; + +class URLSearchParams { + urlcalss:any; + constructor(input:any) { + let out = []; + out = parameterProcessing(input); + this.urlcalss = new urlUtil.URLSearchParams1(); + this.urlcalss.array = out; + } + append(params1:string, params2:string) { + this.urlcalss.append(params1, params2); + } + + set(setname:string, setvalues:string) { + this.urlcalss.set(setname, setvalues); + } + + sort() { + this.urlcalss.sort(); + } + + has(hasname:string) { + return this.urlcalss.has(hasname); + } + + toString() { + return this.urlcalss.toString(); + } + + keys() { + return this.urlcalss.keys(); + } + + values() { + return this.urlcalss.values(); + } + + getAll(getAllname:string) { + return this.urlcalss.getAll(getAllname); + } + + get(getname:string) { + return this.urlcalss.get(getname); + } + + entries() { + + return this.urlcalss.entries(); + } + + delete(deletename:string) { + this.urlcalss.delete(deletename); + } + + forEach(objfun:object) { + return this.urlcalss.forEach(objfun); + } + + [Symbol.iterator]() { + return this.urlcalss.entries(); + } + + updateParams(input:any) { + let out = []; + out = parameterProcessing(input); + this.urlcalss.array = out; + } +} + +function toHleString(arg:any) { + return arg.toString(); +} + +function parameterProcessing(input:any) { + if (input === null || typeof input === 'undefined') { + seachParamsArr = []; + return seachParamsArr; + } else if (typeof input === 'object' || typeof input === 'function') { + return initObjectSeachParams(input); + } else { + return initToStringSeachParams(input); + } +} + +function initObjectSeachParams(input:any) { + if (typeof input[Symbol.iterator] === 'function') { + return iteratorMethod(input); + } + return recordMethod(input); +} + +function recordMethod(input:any) { + const keys = Reflect.ownKeys(input); + seachParamsArr = []; + for (let i = 0; i <= keys.length; i++) { + const key = keys[i]; + const desc = Reflect.getOwnPropertyDescriptor(input, key); + if (desc !== undefined && desc.enumerable) { + const typedKey = toHleString(key); + const typedValue = toHleString(input[key]); + seachParamsArr.push(typedKey, typedValue); + } + } + return seachParamsArr; +} + +function iteratorMethod(input:any) { + let pairs = []; + seachParamsArr = []; + for (const pair of input) { + const convertedPair = []; + for (let element of pair) { + convertedPair.push(element); + } + pairs.push(convertedPair); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + console.log('key-value-is-worong'); + } + seachParamsArr.push(pair[0], pair[1]); + } + return seachParamsArr; +} + +function initToStringSeachParams(input:any) { + if (input[0] === '?') { + input = input.slice(1); + } + let strVal = decodeURI(input); + seachParamsArr = urlUtil.stringParmas(strVal); + return seachParamsArr; +} + +class URL { + href_:string = ''; + search_:string = ''; + origin_:string = ''; + username_:string = ''; + password_:string = ''; + hostname_:string = ''; + host_:string = ''; + hash_:string = ''; + protocol_:string = ''; + pathname_:string = ''; + port_:string = ''; + searchParamsClass_:any; + c_info:any; + constructor() { + let nativeUrl:any; + let inputUrl:string = ''; + let inputBase:any; + + if (arguments.length === 1) { + inputUrl = arguments[0]; + if (typeof inputUrl === 'string' && inputUrl.length > 0) { + nativeUrl = new urlUtil.Url(inputUrl); + } else { + console.log('Input parameter error'); + } + } + + if (arguments.length === 2) { + inputUrl = arguments[0]; + inputBase = arguments[1]; + if (typeof inputUrl === 'string') { + if (typeof inputBase === 'string') { + if (inputBase.length > 0) { + nativeUrl = new urlUtil.Url(inputUrl, inputBase); + } else { + console.log('Input parameter error'); + return; + } + } + if (typeof inputBase === 'object') { + let nativeBase = inputBase.getInfo(); + nativeUrl = new urlUtil.Url(inputUrl, nativeBase); + } + } + } + this.c_info = nativeUrl; + if (nativeUrl.onOrOff) { + this.search_ = encodeURI(nativeUrl.search); + this.username_ = encodeURI(nativeUrl.username); + this.password_ = encodeURI(nativeUrl.password); + if (nativeUrl.GetIsIpv6) { + this.hostname_ = nativeUrl.hostname; + this.host_ = nativeUrl.host; + } else { + this.hostname_ = encodeURI(nativeUrl.hostname); + this.host_ = encodeURI(nativeUrl.host); + } + this.hash_ = encodeURI(nativeUrl.hash); + this.protocol_ = encodeURI(nativeUrl.protocol); + this.pathname_ = encodeURI(nativeUrl.pathname); + this.port_ = nativeUrl.port; + this.origin_ = nativeUrl.protocol + '//' + nativeUrl.host; + this.searchParamsClass_ = new URLSearchParams(this.search_); + this.set_href(); + } else { + console.log('constructor failed'); + } + } + getInfo() { + return this.c_info; + } + toString() { + return this.href_; + } + + get protocol() { + return this.protocol_; + } + set protocol(scheme) { + if (scheme.length === 0) { + return; + } + if (this.protocol_ === 'file:' + && (this.host_ === '' || this.host_ == null)) { + return; + } + this.c_info.protocol = scheme; + this.protocol_ = this.c_info.protocol; + this.set_href() + } + get origin() { + let kOpaqueOrigin = 'null'; + switch (this.protocol_) { + case 'ftp:': + case 'gopher:': + case 'http:': + case 'https:': + case 'ws:': + case 'wss:': + return this.origin_; + } + return kOpaqueOrigin; + } + get username() { + return this.username_; + } + set username(input) { + if (this.host_ == null || this.host_ === '' || this.protocol_ === 'file:') { + return; + } + const usname_ = escape(input); + this.c_info.username = usname_; + this.username_ = this.c_info.username; + this.set_href(); + } + get password() { + return this.password_; + } + set password(input) { + if (this.host_ == null || this.host_ === '' || this.protocol_ === 'file:') { + return; + } + const passwd_ = escape(input); + this.c_info.password = passwd_; + this.password_ = this.c_info.password; + this.set_href(); + } + get hash() { + return this.hash_; + } + set hash(fragment) { + const fragment_ = encodeURI(fragment); + this.c_info.hash = fragment_; + this.hash_ = this.c_info.hash; + this.set_href(); + } + get search() { + return this.search_; + } + set search(query) { + const query_ = encodeURI(query); + this.c_info.search = query_; + this.search_ = this.c_info.search; + this.searchParamsClass_.updateParams(this.search_); + this.set_href(); + } + get hostname() { + return this.hostname_; + } + set hostname(hostname) { + this.c_info.hostname = hostname; + if (this.c_info.GetIsIpv6) { + this.hostname_ = this.c_info.hostname; + } else { + this.hostname_ = encodeURI(this.c_info.hostname); + } + this.set_href(); + } + get host() { + return this.host_; + } + set host(host_) { + this.c_info.host = host_; + if (this.c_info.GetIsIpv6) { + this.host_ = this.c_info.host; + this.hostname_ = this.c_info.hostname; + this.port_ = this.c_info.port; + } else { + this.host_ = encodeURI(this.c_info.host); + this.hostname_ = encodeURI(this.c_info.hostname); + this.port_ = this.c_info.port; + } + this.set_href(); + } + get port() { + return this.port_; + } + set port(port) { + if (this.host_ === '' || this.protocol_ === 'file:' || port === '') { + return; + } + this.c_info.port = port; + this.port_ = this.c_info.port; + this.set_href(); + } + get href() { + return this.href_; + } + set href(href_) { + this.c_info.href(href_); + if (this.c_info.onOrOff) { + this.search_ = encodeURI(this.c_info.search); + this.username_ = encodeURI(this.c_info.username); + this.password_ = encodeURI(this.c_info.password); + if (this.c_info.GetIsIpv6) { + this.hostname_ = this.c_info.hostname; + this.host_ = this.c_info.host; + } else { + this.hostname_ = encodeURI(this.c_info.hostname); + this.host_ = encodeURI(this.c_info.host); + } + this.hash_ = encodeURI(this.c_info.hash); + this.protocol_ = encodeURI(this.c_info.protocol); + this.pathname_ = encodeURI(this.c_info.pathname); + this.port_ = this.c_info.port; + this.origin_ = this.protocol_ + '//' + this.host_; + this.searchParamsClass_.updateParams(this.search_); + this.set_href(); + } + } + + get pathname() { + return this.pathname_; + } + set pathname(path) { + const path_ = encodeURI(path); + this.c_info.pathname = path_; + this.pathname_ = this.c_info.pathname; + this.set_href(); + } + + get searchParams() { + return this.searchParamsClass_; + } + + toJSON() { + return this.href_; + } + set_href() { + let temp = this.protocol_; + if (this.hostname_ !== '') { + temp += '//'; + if (this.password_ !== '' || this.username_ !== '') { + if (this.username_ !== '') { + temp += this.username_; + } + if (this.password_ !== '') { + temp += ':'; + temp += this.password_; + } + temp += '@'; + } + temp += this.hostname_; + if (this.port_ !== '') { + temp += ':'; + temp += this.port_; + } + } else if (this.protocol_ === 'file:') { + temp += '//'; + } + temp += this.pathname_; + if (this.search_) { + temp += this.search_; + } + if (this.hash_) { + temp += this.hash_; + } + this.href_ = temp; + } +} + +export default { + URLSearchParams: URLSearchParams, + URL: URL, +} diff --git a/url/tsconfig.json b/url/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..66ad148561b08a71630eb07c7484394c2acc7930 --- /dev/null +++ b/url/tsconfig.json @@ -0,0 +1,14 @@ +{ +"compilerOptions": { + "target": "es6", + "module": "es6", + "rootDir": "./src", + //"outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./out", /* Specify an output folder for all emitted files. */ + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "noImplicitThis": false, + } +}