Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
the-flagship committed Oct 20, 2022
1 parent 7fa8aa0 commit 0be24a3
Show file tree
Hide file tree
Showing 13 changed files with 817 additions and 1 deletion.
1 change: 1 addition & 0 deletions .envrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use nix
22 changes: 22 additions & 0 deletions .github/workflows/npm-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: Publish Package to npmjs

on:
release:
types: [ published ]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- uses: actions/setup-node@v3
with:
node-version: '16.x'
registry-url: 'https://registry.npmjs.org'

- run: npm ci

- run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
104 changes: 104 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.envrc
shell.nix
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Sweat Equity Ventures

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,23 @@
# armada-cli
# armada-cli

A command line tool for working with the Armada Network.

## Installation

```sh
npm install armada-cli
```

## Usage

### Creating a Bundle

Once a site has been built and is ready for bundling, run the following command to generate an Armada Network compatible tarball:

```sh
npx armada bundle <archive> <build-dir>
```

Example: `npx armada bundle mysite.tgz ./dist`

Note that running `bundle` will also print the SHA256 checksum of the archive, which is needed for publishing the site to the Armada Network.
25 changes: 25 additions & 0 deletions checksum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createHash } from 'crypto';
import { createReadStream } from 'fs';

export async function sha1File(path) {
return hashFile('sha1', path);
}

export async function sha256File(path) {
return hashFile('sha256', path);
}

async function hashFile(algorithm, path) {
const hash = createHash(algorithm);
hash.setEncoding('hex');

return new Promise((resolve, reject) => {
const fd = createReadStream(path);
fd.on('end', () => {
hash.end();
resolve(hash.read());
});
fd.on('error', reject);
fd.pipe(hash);
});
}
82 changes: 82 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env node

import * as path from 'path';
import * as tar from 'tar';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import { sha256File } from './checksum.js';
import { generateManifest } from './manifest.js';

yargs(hideBin(process.argv))
.command(
'bundle <archive> <build-dir>',
'Bundle an application for use on the Armada Network',
(yargs) => {
return yargs
.positional('archive', {
describe: 'The output archive to create (e.g. site.tgz)',
})
.positional('build-dir', {
describe: 'Relative path to the build directory (e.g. ./dist)',
})
},
async (argv) => {
const manifestPath = await generateManifest(argv.buildDir);
console.log(`Successfully created manifest: ${manifestPath}`);

await compress(argv.archive, argv.buildDir);
console.log(`Successfully created archive: ${argv.archive}`);

const sum = await sha256File(argv.archive);
console.log(`${argv.archive} has SHA256 checksum: ${sum}`);
}
)
.command(
'checksum <file>',
'Prints the SHA256 checksum of the provided file',
(yargs) => {
return yargs
.positional('file', {
describe: 'The file to checksum',
})
},
async (argv) => {
console.log(await sha256File(argv.file));
}
)
.command(
'generate-manifest <build-dir>',
'Generate a new site manifest',
(yargs) => {
return yargs
.positional('build-dir', {
describe: 'Relative path to the build directory (e.g. ./dist)',
})
},
async (argv) => {
const manifestPath = await generateManifest(argv.buildDir);
console.log(`Successfully created manifest: ${manifestPath}`);
}
)
.demandCommand(1)
.parse();

async function compress(archive, buildDir) {
return tar.c(
{
gzip: true,
file: archive,

// Always change directories to the immediate parent of buildDir before
// archiving so that the final file structure is one level deep.
C: path.join(buildDir, '..'),

// Follow symlinks, the network will only serve regular files.
follow: true,
},
[
// Due to the `C` flag used above, only specify the final path component.
path.basename(buildDir)
]
);
}
39 changes: 39 additions & 0 deletions filesystem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Adapted from https://github.com/angular/angular/blob/59aa2c06d1bee5c671a4c0ba3a2d98f0cc8bffd6/packages/service-worker/cli/filesystem.ts

import * as fs from 'fs';
import * as path from 'path';

export class NodeFilesystem {
constructor(base) {
this.base = base;
}

async list(_path) {
const dir = this.canonical(_path);
const entries = fs.readdirSync(dir).map(
(entry) => ({ entry, stats: fs.statSync(path.join(dir, entry)) }));
const files = entries.filter((entry) => !entry.stats.isDirectory())
.map((entry) => path.posix.join(_path, entry.entry));

return entries.filter((entry) => entry.stats.isDirectory())
.map((entry) => path.posix.join(_path, entry.entry))
.reduce(
async (list, subdir) =>
(await list).concat(await this.list(subdir)),
Promise.resolve(files));
}

async read(_path) {
const file = this.canonical(_path);
return fs.readFileSync(file).toString();
}

async write(_path, contents) {
const file = this.canonical(_path);
fs.writeFileSync(file, contents);
}

canonical(_path) {
return path.posix.join(this.base, _path);
}
}
48 changes: 48 additions & 0 deletions manifest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { sha256File } from './checksum.js';
import { NodeFilesystem } from './filesystem.js';

const MANIFEST_FILENAME = 'armada.json';
const MANIFEST_PATH = '/' + MANIFEST_FILENAME;

function newManifest() {
return {
configVersion: 1,
timestamp: Date.now(),
index: '/index.html',
assetGroups: [
{
name: 'main',
installMode: 'lazy',
updateMode: 'lazy',
cacheQueryOptions: { 'ignoreVary': true },
urls: [],
patterns: [],
},
],
dataGroups: [],
hashTable: {},
navigationUrls: [
{ positive: true, regex: '^\\/.*$' },
{ positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$' },
{ positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$' },
{ positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$' },
],
navigationRequestStrategy: 'performance',
};
}

export async function generateManifest(buildDir) {
const manifest = newManifest();
const fs = new NodeFilesystem(buildDir);

const files = (await fs.list('/')).filter(val => val != MANIFEST_PATH);
for (const fPath of files) {
const hash = await sha256File(fs.canonical(fPath));
const url = encodeURI(fPath);
manifest.assetGroups[0].urls.push(url);
manifest.hashTable[url] = hash;
}

fs.write(MANIFEST_FILENAME, JSON.stringify(manifest, null, 2));
return fs.canonical(MANIFEST_FILENAME);
}
Loading

0 comments on commit 0be24a3

Please sign in to comment.