Explorar el Código

feat: upgrade to new napi

LongYinan hace 5 años
padre
commit
de53c5c034

+ 15 - 2
.github/workflows/CI.yaml

@@ -1,5 +1,8 @@
 name: CI
 name: CI
 
 
+env:
+  DEBUG: 'napi:*'
+
 on:
 on:
   push:
   push:
     branches: [master, develop]
     branches: [master, develop]
@@ -78,13 +81,20 @@ jobs:
         run: yarn install --frozen-lockfile --registry https://registry.npmjs.org
         run: yarn install --frozen-lockfile --registry https://registry.npmjs.org
 
 
       - name: 'Build'
       - name: 'Build'
+        if: matrix.os != 'macos-latest'
         run: yarn build
         run: yarn build
 
 
+      - name: 'Build'
+        if: matrix.os == 'macos-latest'
+        run: yarn build
+        env:
+          MACOSX_DEPLOYMENT_TARGET: '10.13'
+
       - name: Upload artifact
       - name: Upload artifact
         uses: actions/upload-artifact@v2
         uses: actions/upload-artifact@v2
         with:
         with:
           name: bindings-${{ env.PLATFORM_NAME }}
           name: bindings-${{ env.PLATFORM_NAME }}
-          path: index.${{ env.PLATFORM_NAME }}.node
+          path: package-template.${{ env.PLATFORM_NAME }}.node
 
 
       - name: Clear the cargo caches
       - name: Clear the cargo caches
         run: |
         run: |
@@ -170,7 +180,10 @@ jobs:
       - name: Download all artifacts
       - name: Download all artifacts
         uses: actions/download-artifact@v2
         uses: actions/download-artifact@v2
         with:
         with:
-          path: .
+          path: artifacts
+
+      - name: Move artifacts
+        run: yarn artifacts
 
 
       - name: List packages
       - name: List packages
         run: ls -R .
         run: ls -R .

+ 5 - 2
Cargo.toml

@@ -10,12 +10,15 @@ edition = "2018"
 crate-type = ["cdylib"]
 crate-type = ["cdylib"]
 
 
 [dependencies]
 [dependencies]
-napi = { version = "0.4" }
-napi-derive = { version = "0.4" }
+napi = { version = "0.5" }
+napi-derive = { version = "0.5" }
 
 
 [target.'cfg(all(unix, not(target_env = "musl")))'.dependencies]
 [target.'cfg(all(unix, not(target_env = "musl")))'.dependencies]
 jemallocator = { version = "0.3", features = ["disable_initial_exec_tls"] }
 jemallocator = { version = "0.3", features = ["disable_initial_exec_tls"] }
 
 
+[target.'cfg(windows)'.dependencies]
+mimalloc = { version = "0.1" }
+
 [build-dependencies]
 [build-dependencies]
 napi-build = "0.2"
 napi-build = "0.2"
 
 

+ 4 - 3
index.js

@@ -4,9 +4,10 @@ const { loadBinding } = require('@node-rs/helper')
 
 
 try {
 try {
   // __dirname means load native addon from current dir
   // __dirname means load native addon from current dir
-  // 'index' means native addon name is `index`
-  // the value of this two arguments was decided by `build` script in `package.json`
-  module.exports = loadBinding(__dirname, 'index')
+  // 'package-template' means native addon name is `package-template`
+  // the first arguments was decided by `build` script in `package.json`
+  // the second arguments was decided by `napi.name` field in `package.json`
+  module.exports = loadBinding(__dirname, 'package-template')
 } catch (e) {
 } catch (e) {
   try {
   try {
     module.exports = require(`@napi-rs/package-template-${platform()}`)
     module.exports = require(`@napi-rs/package-template-${platform()}`)

+ 2 - 2
npm/darwin/README.md

@@ -1,3 +1,3 @@
-# `@napi-rs/package-template-darwin`
+`#@napi-rs/package-template-darwin`
 
 
-This is the macOS 64-bit binary for `@napi-rs/package-template`.
+this is the **darwin** 64-bit binary for `@napi-rs/package-template`

+ 23 - 7
npm/darwin/package.json

@@ -1,16 +1,32 @@
 {
 {
   "name": "@napi-rs/package-template-darwin",
   "name": "@napi-rs/package-template-darwin",
   "version": "0.0.6",
   "version": "0.0.6",
+  "os": [
+    "darwin"
+  ],
+  "main": "package-template.darwin.node",
+  "files": [
+    "package-template.darwin.node"
+  ],
   "description": "Template project for writing node package with napi-rs",
   "description": "Template project for writing node package with napi-rs",
-  "repository": "git@github.com:napi-rs/package-template.git",
+  "keywords": [
+    "napi-rs",
+    "NAPI",
+    "N-API",
+    "Rust",
+    "node-addon",
+    "node-addon-api"
+  ],
   "license": "MIT",
   "license": "MIT",
-  "keywords": ["napi-rs", "NAPI", "N-API", "Rust", "node-addon", "node-addon-api"],
-  "main": "index.darwin.node",
-  "files": ["index.darwin.node"],
+  "cpu": [
+    "x64"
+  ],
+  "engines": {
+    "node": ">= 8.9"
+  },
   "publishConfig": {
   "publishConfig": {
     "registry": "https://registry.npmjs.org/",
     "registry": "https://registry.npmjs.org/",
     "access": "public"
     "access": "public"
   },
   },
-  "os": ["darwin"],
-  "cpu": ["x64"]
-}
+  "repository": "git@github.com:napi-rs/package-template.git"
+}

+ 2 - 2
npm/linux/README.md

@@ -1,3 +1,3 @@
-# `@napi-rs/package-template-linux`
+`#@napi-rs/package-template-linux`
 
 
-This is the Linux 64-bit binary for `@napi-rs/package-template`.
+this is the **linux** 64-bit binary for `@napi-rs/package-template`

+ 23 - 7
npm/linux/package.json

@@ -1,16 +1,32 @@
 {
 {
   "name": "@napi-rs/package-template-linux",
   "name": "@napi-rs/package-template-linux",
   "version": "0.0.6",
   "version": "0.0.6",
+  "os": [
+    "linux"
+  ],
+  "main": "package-template.linux.node",
+  "files": [
+    "package-template.linux.node"
+  ],
   "description": "Template project for writing node package with napi-rs",
   "description": "Template project for writing node package with napi-rs",
-  "repository": "git@github.com:napi-rs/package-template.git",
+  "keywords": [
+    "napi-rs",
+    "NAPI",
+    "N-API",
+    "Rust",
+    "node-addon",
+    "node-addon-api"
+  ],
   "license": "MIT",
   "license": "MIT",
-  "keywords": ["napi-rs", "NAPI", "N-API", "Rust", "node-addon", "node-addon-api"],
-  "main": "index.linux.node",
-  "files": ["index.linux.node"],
+  "cpu": [
+    "x64"
+  ],
+  "engines": {
+    "node": ">= 8.9"
+  },
   "publishConfig": {
   "publishConfig": {
     "registry": "https://registry.npmjs.org/",
     "registry": "https://registry.npmjs.org/",
     "access": "public"
     "access": "public"
   },
   },
-  "os": ["linux"],
-  "cpu": ["x64"]
-}
+  "repository": "git@github.com:napi-rs/package-template.git"
+}

+ 2 - 2
npm/win32/README.md

@@ -1,3 +1,3 @@
-# `@napi-rs/package-template-win32`
+`#@napi-rs/package-template-win32`
 
 
-This is the Windows 64-bit binary for `@napi-rs/package-template`.
+this is the **win32** 64-bit binary for `@napi-rs/package-template`

+ 23 - 7
npm/win32/package.json

@@ -1,16 +1,32 @@
 {
 {
   "name": "@napi-rs/package-template-win32",
   "name": "@napi-rs/package-template-win32",
   "version": "0.0.6",
   "version": "0.0.6",
+  "os": [
+    "win32"
+  ],
+  "main": "package-template.win32.node",
+  "files": [
+    "package-template.win32.node"
+  ],
   "description": "Template project for writing node package with napi-rs",
   "description": "Template project for writing node package with napi-rs",
-  "repository": "git@github.com:napi-rs/package-template.git",
+  "keywords": [
+    "napi-rs",
+    "NAPI",
+    "N-API",
+    "Rust",
+    "node-addon",
+    "node-addon-api"
+  ],
   "license": "MIT",
   "license": "MIT",
-  "keywords": ["napi-rs", "NAPI", "N-API", "Rust", "node-addon", "node-addon-api"],
-  "main": "index.win32.node",
-  "files": ["index.win32.node"],
+  "cpu": [
+    "x64"
+  ],
+  "engines": {
+    "node": ">= 8.9"
+  },
   "publishConfig": {
   "publishConfig": {
     "registry": "https://registry.npmjs.org/",
     "registry": "https://registry.npmjs.org/",
     "access": "public"
     "access": "public"
   },
   },
-  "os": ["win32"],
-  "cpu": ["x64"]
-}
+  "repository": "git@github.com:napi-rs/package-template.git"
+}

+ 11 - 7
package.json

@@ -9,6 +9,9 @@
   "files": ["index.d.ts", "index.js"],
   "files": ["index.d.ts", "index.js"],
   "os": ["darwin", "linux", "win32"],
   "os": ["darwin", "linux", "win32"],
   "cpu": ["x64"],
   "cpu": ["x64"],
+  "napi": {
+    "name": "package-template"
+  },
   "engines": {
   "engines": {
     "node": ">= 8.9"
     "node": ">= 8.9"
   },
   },
@@ -17,8 +20,9 @@
     "access": "public"
     "access": "public"
   },
   },
   "scripts": {
   "scripts": {
-    "build": "cargo build --release && napi build --platform --release ./index",
-    "build:debug": "cargo build && napi --platform ./index",
+    "artifacts": "napi artifacts",
+    "build": "cargo build --release && napi build --platform --release",
+    "build:debug": "cargo build && napi --platform",
     "format": "run-p format:md format:json format:yaml format:source format:rs",
     "format": "run-p format:md format:json format:yaml format:source format:rs",
     "format:md": "prettier --parser markdown --write './**/*.md'",
     "format:md": "prettier --parser markdown --write './**/*.md'",
     "format:json": "prettier --parser json --write './**/*.json'",
     "format:json": "prettier --parser json --write './**/*.json'",
@@ -26,15 +30,15 @@
     "format:source": "prettier --config ./package.json --write './**/*.{js,ts}'",
     "format:source": "prettier --config ./package.json --write './**/*.{js,ts}'",
     "format:yaml": "prettier --parser yaml --write './**/*.{yml,yaml}'",
     "format:yaml": "prettier --parser yaml --write './**/*.{yml,yaml}'",
     "lint": "eslint . -c ./.eslintrc.yml './**/*.{ts,tsx,js}'",
     "lint": "eslint . -c ./.eslintrc.yml './**/*.{ts,tsx,js}'",
-    "prepublishOnly": "node ./scripts/publish.js",
+    "prepublishOnly": "napi prepublish -t npm",
     "test": "ava",
     "test": "ava",
-    "version": "node ./scripts/version.js"
+    "version": "napi version"
   },
   },
   "devDependencies": {
   "devDependencies": {
     "@octokit/rest": "^18.0.4",
     "@octokit/rest": "^18.0.4",
     "@swc-node/register": "^0.4.5",
     "@swc-node/register": "^0.4.5",
-    "@typescript-eslint/eslint-plugin": "^4.0.0",
-    "@typescript-eslint/parser": "^3.10.1",
+    "@typescript-eslint/eslint-plugin": "^4.0.1",
+    "@typescript-eslint/parser": "^4.0.1",
     "ava": "^3.12.1",
     "ava": "^3.12.1",
     "chalk": "^4.1.0",
     "chalk": "^4.1.0",
     "eslint": "^7.8.1",
     "eslint": "^7.8.1",
@@ -46,7 +50,7 @@
     "eslint-plugin-sonarjs": "^0.5.0",
     "eslint-plugin-sonarjs": "^0.5.0",
     "husky": "^4.2.5",
     "husky": "^4.2.5",
     "lint-staged": "^10.3.0",
     "lint-staged": "^10.3.0",
-    "napi-rs": "^0.2.6",
+    "napi-rs": "^0.3.0",
     "npm-run-all": "^4.1.5",
     "npm-run-all": "^4.1.5",
     "prettier": "^2.1.1",
     "prettier": "^2.1.1",
     "putasset": "^5.0.3",
     "putasset": "^5.0.3",

+ 1 - 0
rustfmt.toml

@@ -0,0 +1 @@
+tab_spaces = 2

+ 0 - 1
scripts/platforms.js

@@ -1 +0,0 @@
-module.exports = ['darwin', 'linux', 'win32']

+ 0 - 27
scripts/publish.js

@@ -1,27 +0,0 @@
-const { execSync } = require('child_process')
-const fs = require('fs')
-const path = require('path')
-
-const platforms = require('./platforms')
-const updatePackageJson = require('./update-package')
-
-const { version } = require('../package.json')
-
-updatePackageJson(path.join(__dirname, '..', 'package.json'), {
-  optionalDependencies: platforms.reduce((acc, cur) => {
-    acc[`@napi-rs/package-template-${cur}`] = `^${version}`
-    return acc
-  }, {}),
-})
-
-for (const name of platforms) {
-  const pkgDir = path.join(__dirname, '..', 'npm', name)
-  const filename = `index.${name}.node`
-  const bindingFile = fs.readFileSync(path.join(__dirname, '..', `bindings-${name}`, filename))
-  fs.writeFileSync(path.join(pkgDir, filename), bindingFile)
-  execSync('npm publish', {
-    cwd: pkgDir,
-    env: process.env,
-    stdio: 'inherit',
-  })
-}

+ 0 - 6
scripts/update-package.js

@@ -1,6 +0,0 @@
-const fs = require('fs')
-
-module.exports = function updatePackageJson(path, partial) {
-  const old = require(path)
-  fs.writeFileSync(path, JSON.stringify({ ...old, ...partial }, null, 2))
-}

+ 0 - 41
scripts/upload-to-release.js

@@ -1,41 +0,0 @@
-const { execSync } = require('child_process')
-const { join } = require('path')
-
-const { Octokit } = require('@octokit/rest')
-const chalk = require('chalk')
-const putasset = require('putasset')
-
-const platforms = require('./platforms')
-
-const version =
-  'v' +
-  execSync('git log -1 --pretty=%B', {
-    encoding: 'utf8',
-  }).trim('')
-
-;(async () => {
-  const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/')
-  const octokit = new Octokit({
-    auth: process.env.GITHUB_TOKEN,
-  })
-  await octokit.repos.createRelease({
-    owner,
-    repo,
-    tag_name: version,
-  })
-  await Promise.all(
-    platforms.map(async (platform) => {
-      const binary = join(__dirname, '..', `bindings-${platform}`, `index.${platform}.node`)
-      const downloadUrl = await putasset(process.env.GITHUB_TOKEN, {
-        owner,
-        repo,
-        tag: version,
-        filename: binary,
-      })
-      console.info(`${chalk.green(binary)} upload success`)
-      console.info(`Download url: ${chalk.blueBright(downloadUrl)}`)
-    }),
-  )
-})().catch((e) => {
-  console.error(e)
-})

+ 0 - 17
scripts/version.js

@@ -1,17 +0,0 @@
-const { execSync } = require('child_process')
-const path = require('path')
-
-const { version } = require('../package.json')
-const platforms = require('./platforms')
-const updatePackageJson = require('./update-package')
-
-for (const name of platforms) {
-  const pkgDir = path.join(__dirname, '..', 'npm', name)
-  updatePackageJson(path.join(pkgDir, 'package.json'), {
-    version,
-  })
-}
-
-execSync('git add .', {
-  stdio: 'inherit',
-})

+ 25 - 21
src/lib.rs

@@ -11,43 +11,47 @@ use napi::{CallContext, Env, JsNumber, JsObject, Module, Result, Task};
 #[global_allocator]
 #[global_allocator]
 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
 
 
+#[cfg(windows)]
+#[global_allocator]
+static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
+
 register_module!(example, init);
 register_module!(example, init);
 
 
 struct AsyncTask(u32);
 struct AsyncTask(u32);
 
 
 impl Task for AsyncTask {
 impl Task for AsyncTask {
-    type Output = u32;
-    type JsValue = JsNumber;
-
-    fn compute(&mut self) -> Result<Self::Output> {
-        use std::thread::sleep;
-        use std::time::Duration;
-        sleep(Duration::from_millis(self.0 as u64));
-        Ok(self.0 * 2)
-    }
-
-    fn resolve(&self, env: &mut Env, output: Self::Output) -> Result<Self::JsValue> {
-        env.create_uint32(output)
-    }
+  type Output = u32;
+  type JsValue = JsNumber;
+
+  fn compute(&mut self) -> Result<Self::Output> {
+    use std::thread::sleep;
+    use std::time::Duration;
+    sleep(Duration::from_millis(self.0 as u64));
+    Ok(self.0 * 2)
+  }
+
+  fn resolve(&self, env: &mut Env, output: Self::Output) -> Result<Self::JsValue> {
+    env.create_uint32(output)
+  }
 }
 }
 
 
 fn init(module: &mut Module) -> Result<()> {
 fn init(module: &mut Module) -> Result<()> {
-    module.create_named_method("sync", sync_fn)?;
+  module.create_named_method("sync", sync_fn)?;
 
 
-    module.create_named_method("sleep", sleep)?;
-    Ok(())
+  module.create_named_method("sleep", sleep)?;
+  Ok(())
 }
 }
 
 
 #[js_function(1)]
 #[js_function(1)]
 fn sync_fn(ctx: CallContext) -> Result<JsNumber> {
 fn sync_fn(ctx: CallContext) -> Result<JsNumber> {
-    let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
+  let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
 
 
-    ctx.env.create_uint32(argument + 100)
+  ctx.env.create_uint32(argument + 100)
 }
 }
 
 
 #[js_function(1)]
 #[js_function(1)]
 fn sleep(ctx: CallContext) -> Result<JsObject> {
 fn sleep(ctx: CallContext) -> Result<JsObject> {
-    let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
-    let task = AsyncTask(argument);
-    ctx.env.spawn(task)
+  let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
+  let task = AsyncTask(argument);
+  ctx.env.spawn(task)
 }
 }

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 258 - 279
yarn.lock