Namespace gets overwritten using rollup generated files - bundler

Rollup Version: 0.66.6
Operating System (or Browser): Mac, Chrome
Node Version: 10.13.0
Generate script using rollup with this configuration
const outputFileNamespace = "Foo";
const baseObject = {
input: 'js/modules/',
output: {
name: outputFileNamespace,
format: 'iife',
sourcemap: true,
banner: "/*Copyright text*/"
},
plugins: [(environment === PROD_ENV) && uglify()]
};
2. Generate multiple files using this configuration : js1.js , js2.js
3. Load these files in browser, namespace gets overriden
Expected Behavior
If we need to generate multiple output files with the common global namespace as "Foo" here, there should be some check in the generated file which checks for the existence of a global namespace
Actual Behavior
Namespace gets overwritten and the latter one js functions are available

Use a dot separated namespace for each build such as app.foo or use the option output.extend for extending instead of replacing the given namespace.

Related

FUNCTION_REGION env variable in Nodejs is differenrent than GCP set automatically for logs

I programmatically write the logs from the function using such code:
import {Logging} from '#google-cloud/logging';
const logging = new Logging();
const log = logging.log('log-name');
const metadata = {
type: 'cloud_function',
labels: {
function_name: process.env.FUNCTION_NAME,
project: process.env.GCLOUD_PROJECT,
region: process.env.FUNCTION_REGION
},
};
log.write(
log.entry(metadata, "some message")
);
Later in Logs Explorer I get the log message where labels.region is us1 whereas standard logs that GCP adds, e.g. "Function execution started", contains us-central1 value.
Should not they be the same? Maybe I missed something or if it was done intentionally what is the reason behind it?
process.env.FUNCTION_REGION is supported only in Node 8 runtime. In newer runtimes it was deprecated. More info in documentation.
If your function requires one of the environment variables from an older runtime, you can set the variable when deploying your function.

Using terraform yamldecode to access multi level element

I have a yaml file (also used in a azure devops pipeline so needs to be in this format) which contains some settings I'd like to directly access from my terraform module.
The file looks something like:
variables:
- name: tenantsList
value: tenanta,tenantb
- name: unitName
value: canary
I'd like to have a module like this to access the settings but I can't see how to get to the bottom level:
locals {
settings = yamldecode(file("../settings.yml"))
}
module "infra" {
source = "../../../infra/terraform/"
unitname = local.settings.variables.unitName
}
But the terraform plan errors with this:
Error: Unsupported attribute
on canary.tf line 16, in module "infra":
16: unitname = local.settings.variables.unitName
|----------------
| local.settings.variables is tuple with 2 elements
This value does not have any attributes.
It seems like the main reason this is difficult is because this YAML file is representing what is logically a single map but is physically represented as a YAML list of maps.
When reading data from a separate file like this, I like to write an explicit expression to normalize it and optionally transform it for more convenient use in the rest of the Terraform module. In this case, it seems like having variables as a map would be the most useful representation as a Terraform value, so we can write a transformation expression like this:
locals {
raw_settings = yamldecode(file("${path.module}/../settings.yml"))
settings = {
variables = tomap({
for v in local.raw_settings.variables : v.name => v.value
})
}
}
The above uses a for expression to project the list of maps into a single map using the name values as the keys.
With the list of maps converted to a single map, you can then access it the way you originally tried:
module "infra" {
source = "../../../infra/terraform/"
unitname = local.settings.variables.unitName
}
If you were to output the transformed value of local.settings as YAML, it would look something like this, which is why accessing the map elements directly is now possible:
variables:
tenantsList: tenanta,tenantb
unitName: canary
This will work only if all of the name strings in your input are unique, because otherwise there would not be a unique map key for each element.
(Writing a normalization expression like this also doubles as some implicit validation for the shape of that YAML file: if variables were not a list or if the values were not all of the same type then Terraform would raise a type error evaluating that expression. Even if no transformation is required, I like to write out this sort of expression anyway because it serves as some documentation for what shape the YAML file is expected to have, rather than having to study all of the references to it throughout the rest of the configuration.)
With my multidecoder for YAML and JSON you are able to access multiple YAML and/or JSON files with their relative paths in one step.
Documentations can be found here:
Terraform Registry -
https://registry.terraform.io/modules/levmel/yaml_json/multidecoder/latest?tab=inputs
GitHub:
https://github.com/levmel/terraform-multidecoder-yaml_json
Usage
Place this module in the location where you need to access multiple different YAML and/or JSON files (different paths possible) and pass
your path/-s in the parameter filepaths which takes a set of strings of the relative paths of YAML and/or JSON files as an argument. You can change the module name if you want!
module "yaml_json_decoder" {
source = "levmel/yaml_json/multidecoder"
version = "0.2.1"
filepaths = ["routes/nsg_rules.yml", "failover/cosmosdb.json", "network/private_endpoints/*.yaml", "network/private_links/config_file.yml", "network/private_endpoints/*.yml", "pipeline/config/*.json"]
}
Patterns to access YAML and/or JSON files from relative paths:
To be able to access all YAML and/or JSON files in a folder entern your path as follows "folder/rest_of_folders/*.yaml", "folder/rest_of_folders/*.yml" or "folder/rest_of_folders/*.json".
To be able to access a specific YAML and/or a JSON file in a folder structure use this "folder/rest_of_folders/name_of_yaml.yaml", "folder/rest_of_folders/name_of_yaml.yml" or "folder/rest_of_folders/name_of_yaml.json"
If you like to select all YAML and/or JSON files within a folder, then you should use "*.yml", "*.yaml", "*.json" format notation. (see above in the USAGE section)
YAML delimiter support is available from version 0.1.0!
WARNING: Only the relative path must be specified. The path.root (it is included in the module by default) should not be passed, but everything after it.
Access YAML and JSON entries
Now you can access all entries within all the YAML and/or JSON files you've selected like that: "module.yaml_json_decoder.files.[name of your YAML or JSON file].entry". If the name of your YAML or JSON file is "name_of_your_config_file" then access it as follows "module.yaml_json_decoder.files.name_of_your_config_file.entry".
Example of multi YAML and JSON file accesses from different paths (directories)
first YAML file:
routes/nsg_rules.yml
rdp:
name: rdp
priority: 80
direction: Inbound
access: Allow
protocol: Tcp
source_port_range: "*"
destination_port_range: 3399
source_address_prefix: VirtualNetwork
destination_address_prefix: "*"
---
ssh:
name: ssh
priority: 70
direction: Inbound
access: Allow
protocol: Tcp
source_port_range: "*"
destination_port_range: 24
source_address_prefix: VirtualNetwork
destination_address_prefix: "*"
second YAML file:
services/logging/monitoring.yml
application_insights:
application_type: other
retention_in_days: 30
daily_data_cap_in_gb: 20
daily_data_cap_notifications_disabled: true
logs:
# Optional fields
- "AppMetrics"
- "AppAvailabilityResults"
- "AppEvents"
- "AppDependencies"
- "AppBrowserTimings"
- "AppExceptions"
- "AppExceptions"
- "AppPerformanceCounters"
- "AppRequests"
- "AppSystemEvents"
- "AppTraces"
first JSON file:
test/config/json_history.json
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
main.tf
module "yaml_json_multidecoder" {
source = "levmel/yaml_json/multidecoder"
version = "0.2.1"
filepaths = ["routes/nsg_rules.yml", "services/logging/monitoring.yml", test/config/*.json]
}
output "nsg_rules_entry" {
value = module.yaml_json_multidecoder.files.nsg_rules.aks.ssh.source_address_prefix
}
output "application_insights_entry" {
value = module.yaml_json_multidecoder.files.monitoring.application_insights.daily_data_cap_in_gb
}
output "json_history" {
value = module.yaml_json_multidecoder.files.json_history.glossary.title
}
Changes to Outputs:
nsg_rules_entry = "VirtualNetwork"
application_insights_entry = 20
json_history = "example glossary"

How to graphql-codegen handle schema with string templates in typescript/javascript exports

I am using graphql-codegen to generate the typescript type files for given schema.
All good except if there is string template in the exported scheme, it will complain the sytax and seems it will not compile it. Check the following files for more details.
The types.js is below:
const gql = require("graphql-tag");
const Colors = ["Red", "Yellow"];
export default gql`
type Person {
name: String
}
enum Color {
${Colors.join("\n")}
}
# if we change the above enum to be the below, it will be good
# enum Color {
# Red
# Yellow
# }
`;
And the config yml file is:
schema:
- types.js
generates:
generated.ts:
plugins:
- typescript
- typescript-resolvers
When run yarn graphql:codegen, it complains the below:
Found 1 error
✖ generated.ts
Failed to load schema from types.js:
Syntax Error: Expected Name, found }
GraphQLError: Syntax Error: Expected Name, found }
at syntaxError (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/error/syntaxError.js:15:10)
at Parser.expectToken (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1404:40)
at Parser.parseName (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:94:22)
at Parser.parseEnumValueDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1014:21)
at Parser.optionalMany (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1497:28)
at Parser.parseEnumValuesDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1002:17)
at Parser.parseEnumTypeDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:986:23)
at Parser.parseTypeSystemDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:705:23)
at Parser.parseDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:146:23)
at Parser.many (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1518:26)
at Parser.parseDocument (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:111:25)
at Object.parse (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:36:17)
at Object.parseGraphQLSDL (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/#graphql-toolkit/common/index.cjs.js:572:28)
at CodeFileLoader.load (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/#graphql-toolkit/code-file-loader/index.cjs.js:120:31)
at async /Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/#graphql-toolkit/core/index.cjs.js:682:25
at async Promise.all (index 0)
GraphQL Code Generator supports:
- ES Modules and CommonJS exports (export as default or named export "schema")
- Introspection JSON File
- URL of GraphQL endpoint
- Multiple files with type definitions (glob expression)
- String in config file
Try to use one of above options and run codegen again.
Error: Failed to load schema
at loadSchema (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/#graphql-codegen/cli/bin.js:353:15)
Error: Failed to load schema
at loadSchema (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/#graphql-codegen/cli/bin.js:353:15)
Looks like graphql-codegen didn't like template string like: ${Colors.join('\n')}.
Also please have a look about the repo containing all the above files.
Anyone can help to fix? Thanks.
It's not handling it, mostly because of the complexity of loading code files and interpolate it.
But, the way to workaround is:
Create a single schema.js file.
Import all typedefs with string interpolation from your source files, and use buildSchema (from graphql) or makeExecutableSchema (from graphql-tools) to build a GraphQLSchema object instance.
Export your GraphQLSchema as default export, or as identifier named schema.
Provide that file into codegen (by doing schema: ./schema.js - using a single code file causes the codegen to look for ast code, and then try to do require to it.
If you are using TypeScript, you should also add require extension to the codegen (see https://graphql-code-generator.com/docs/getting-started/require-field#typescript-support)

Where is my GenesisConfig entry for my config storage?

I'm trying to reconstruct the Sudo module's root key behaviour before I extend it. Following the v1 documentation on GenesisConfig, I have a config() storage variable in my decl_storage:
RootKey get(fn rootkey) config(): T::AccountId;
(in the node-template template.rs for now)
Yet, if I look at the macro-expanded output, I have no template item in the GenesisConfig struct, and I cannot put in an entry like the following in the chain_spec's testnet_genesis function
template: Some(TemplateConfig {
rootkey: root_key,
}),
Because I get a complaint about both template and TemplateConfig, even though both are supposed to be constructed by the macro expansion.
Edit: Specifically, if it add the above with a TemplateConfig item in the use runtime::{} list, I am informed:
error[E0432]: unresolved import `runtime::TemplateConfig`
--> node-template/src/chain_spec.rs:4:14
|
4 | SudoConfig, TemplateConfig, IndicesConfig, SystemConfig, WASM_BINARY, Signature
| ^^^^^^^^^^^^^^ no `TemplateConfig` in the root
error[E0560]: struct `node_template_runtime::GenesisConfig` has no field named `template`
--> node-template/src/chain_spec.rs:142:3
|
142 | template: Some(TemplateConfig {
| ^^^^^^^^ `node_template_runtime::GenesisConfig` does not have this field
|
= note: available fields are: `system`, `aura`, `grandpa`, `indices`, `balances`, `sudo`
I also don't see any template items in polkadot.js under storage, whereas I do see sudo's key().
What obvious thing am I missing?
When trying to set up the genesis configuration for a runtime module you need to do the following:
Make sure your runtime module has "configurable storage items". This could be as simple as setting config() in the decl_storage! macro, but could also be a bit more complicated as documented here: `decl_storage! - GenesisConfig.
decl_storage! {
trait Store for Module<T: Trait> as Sudo {
Key get(fn key) config(): T::AccountId;
//--------------^^^^^^^^---------------
}
}
This will generate a GenesisConfig in your module, which will be used in the next step.
Next you need to expose your module specific GenesisConfig struct to the rest of your runtime's genesis configuration by adding the Config/Config<T> item to your construct_runtime! macro. In this example, we use Config<T> because we are configuring a generic T::AccountId:
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = opaque::Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
//--snip--
TemplateModule: template::{Module, Call, Storage, Event<T>, Config<T>},
//----------------------------------------------------------^^^^^^^^^--
}
}
This will generate an alias to your module specific GenesisConfig object based on the name you configured for your module (name + Config). In this case, the name of the object will be TemplateModuleConfig.
Finally, you need to configure this storage item in the chain_spec.rs file. To do this, make sure to import the TemplateModuleConfig item:
use node_template_runtime::{
AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig,
SudoConfig, IndicesConfig, SystemConfig, WASM_BINARY, Signature,
TemplateModuleConfig,
//--^^^^^^^^^^^^^^^^^^^^
};
And then configure your genesis information:
template: Some(TemplateModuleConfig {
key: root_key,
}),
It sounds like you're missing use TemplateConfig at the beginning of your chain_spec.rs file. Something like this https://github.com/substrate-developer-hub/substrate-node-template/blob/8fea1dc6dd0c5547117d022fd0d1bf49868ee548/src/chain_spec.rs#L4
If this is not your issue please supply the exact error you're getting, and optionally a link to the full code.

Extract scss into multiple files using extract-text-webpack-plugin?

My folder structure is like this
|
|-scss/
|-main1.scss
|-main2.scss
Is it possible to use extract-text-webpack-plugin to extract these two entry points two separate files?
Currently, I'm getting it as a single file.
If you specify the two entry points in your webpack config like so:
entry: {
main1: __dirname + '/src/main1.js',
main2: __dirname + '/src/main2.js',
},
ouput: {
path: __dirname,
filename: '[name].js'
}
I assume your main1.scss is imported in the main1.js file, and main2.scss is imported in main2.js.
You can then use the [name] placeholder on the extract-text-webpack-plugin, which should create a separate output file for each entry point:
plugins: [
new ExtractTextPlugin('[name].css')
]
This should output two separate css files for you: main1.css and main2.css
Hope this helps!

Resources